MOBI Input: Upshift non-animated GIF to PNG as it is a more widely supported format

This commit is contained in:
Kovid Goyal 2020-03-10 13:50:28 +05:30
parent 3df15e222a
commit 4a661f9138
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 23 additions and 3 deletions

View File

@ -21,7 +21,7 @@ from calibre.ebooks.metadata import MetaInformation
from calibre.ebooks.metadata.opf2 import OPFCreator, OPF
from calibre.ebooks.metadata.toc import TOC
from calibre.ebooks.mobi.reader.headers import BookHeader
from calibre.utils.img import save_cover_data_to
from calibre.utils.img import save_cover_data_to, gif_data_to_png_data, AnimatedGIF
from calibre.utils.imghdr import what
from polyglot.builtins import iteritems, unicode_type, range, map
@ -897,9 +897,15 @@ class MobiReader(object):
continue
if imgfmt == 'jpeg':
imgfmt = 'jpg'
if imgfmt == 'gif':
try:
data = gif_data_to_png_data(data)
imgfmt = 'png'
except AnimatedGIF:
pass
path = os.path.join(output_dir, '%05d.%s' % (image_index, imgfmt))
image_name_map[image_index] = os.path.basename(path)
if imgfmt in ('gif', 'png'):
if imgfmt == 'png':
with open(path, 'wb') as f:
f.write(data)
else:

View File

@ -67,7 +67,7 @@ def load_jxr_data(data):
# }}}
# png to gif {{{
# png <-> gif {{{
def png_data_to_gif_data(data):
@ -91,6 +91,20 @@ def png_data_to_gif_data(data):
img.save(buf, 'gif')
return buf.getvalue()
class AnimatedGIF(ValueError):
pass
def gif_data_to_png_data(data, discard_animation=False):
from PIL import Image
img = Image.open(BytesIO(data))
if img.is_animated and not discard_animation:
raise AnimatedGIF()
buf = BytesIO()
img.save(buf, 'png')
return buf.getvalue()
# }}}
# Loading images {{{