From 9e2a7fca94c9b2f2c37937827f1d5b0b37407393 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Fri, 20 Aug 2021 11:36:46 +0530 Subject: [PATCH] MOBI Output: Fix JPEG images without any JFIF metadata not being rendered on the Kindle --- src/calibre/ebooks/mobi/writer2/resources.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/calibre/ebooks/mobi/writer2/resources.py b/src/calibre/ebooks/mobi/writer2/resources.py index 9647793e4d..ba8c776a64 100644 --- a/src/calibre/ebooks/mobi/writer2/resources.py +++ b/src/calibre/ebooks/mobi/writer2/resources.py @@ -7,6 +7,8 @@ __docformat__ = 'restructuredtext en' import os +from PIL import Image +from io import BytesIO from calibre.ebooks.mobi import MAX_THUMB_DIMEN, MAX_THUMB_SIZE from calibre.ebooks.mobi.utils import (rescale_image, mobify_image, @@ -20,6 +22,16 @@ PLACEHOLDER_GIF = b'GIF89a\x01\x00\x01\x00\xf0\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00!\xfe calibre-placeholder-gif-for-azw3\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;' # noqa +def ensure_jpeg_has_jfif(data: bytes) -> bytes: + # Amazon's MOBI renderer can render JPEG images without JFIF metadata + img = Image.open(BytesIO(data)) + if img.format == 'JPEG' and not img.info: + out = BytesIO() + img.save(out, img.format) + data = out.getvalue() + return data + + class Resources(object): def __init__(self, oeb, opts, is_periodical, add_fonts=False, @@ -44,7 +56,7 @@ def process_image(self, data): return data func = mobify_image if self.opts.mobi_keep_original_images else rescale_image try: - return func(data) + return ensure_jpeg_has_jfif(func(data)) except Exception: if 'png' != what(None, data): raise