New download: Do not convert all downloaded images to JPG format. This fixes the problem of PNG images with transparent backgrounds being rendered with black backgrounds

This commit is contained in:
Kovid Goyal 2013-01-22 22:32:15 +05:30
parent 4cf17349af
commit 993fdfa34e

View File

@ -10,8 +10,6 @@ UTF-8 encoding with any charset declarations removed.
import sys, socket, os, urlparse, re, time, copy, urllib2, threading, traceback, imghdr import sys, socket, os, urlparse, re, time, copy, urllib2, threading, traceback, imghdr
from urllib import url2pathname, quote from urllib import url2pathname, quote
from httplib import responses from httplib import responses
from PIL import Image
from cStringIO import StringIO
from base64 import b64decode from base64 import b64decode
from calibre import browser, relpath, unicode_path from calibre import browser, relpath, unicode_path
@ -21,6 +19,8 @@ from calibre.ebooks.BeautifulSoup import BeautifulSoup, Tag
from calibre.ebooks.chardet import xml_to_unicode from calibre.ebooks.chardet import xml_to_unicode
from calibre.utils.config import OptionParser from calibre.utils.config import OptionParser
from calibre.utils.logging import Log from calibre.utils.logging import Log
from calibre.utils.magick import Image
from calibre.utils.magick.draw import identify_data
class FetchError(Exception): class FetchError(Exception):
pass pass
@ -374,8 +374,8 @@ class RecursiveFetcher(object):
fname = ascii_filename('img'+str(c)) fname = ascii_filename('img'+str(c))
if isinstance(fname, unicode): if isinstance(fname, unicode):
fname = fname.encode('ascii', 'replace') fname = fname.encode('ascii', 'replace')
imgpath = os.path.join(diskpath, fname+'.jpg') itype = imghdr.what(None, data)
if (imghdr.what(None, data) is None and b'<svg' in data[:1024]): if itype is None and b'<svg' in data[:1024]:
# SVG image # SVG image
imgpath = os.path.join(diskpath, fname+'.svg') imgpath = os.path.join(diskpath, fname+'.svg')
with self.imagemap_lock: with self.imagemap_lock:
@ -385,11 +385,18 @@ class RecursiveFetcher(object):
tag['src'] = imgpath tag['src'] = imgpath
else: else:
try: try:
im = Image.open(StringIO(data)).convert('RGBA') if itype not in {'png', 'jpg', 'jpeg'}:
itype == 'png' if itype == 'gif' else 'jpg'
im = Image()
im.load(data)
data = im.export(itype)
else:
identify_data(data)
imgpath = os.path.join(diskpath, fname+'.'+itype)
with self.imagemap_lock: with self.imagemap_lock:
self.imagemap[iurl] = imgpath self.imagemap[iurl] = imgpath
with open(imgpath, 'wb') as x: with open(imgpath, 'wb') as x:
im.save(x, 'JPEG') x.write(data)
tag['src'] = imgpath tag['src'] = imgpath
except: except:
traceback.print_exc() traceback.print_exc()