diff --git a/serve/server.py b/serve/server.py index a1e4d407..da973350 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1753,10 +1753,24 @@ class Vision: raise ValueError(too_big) return data + @staticmethod + def _exif_rotated(data: bytes) -> bool: + """A JPEG whose EXIF Orientation says it is stored turned (phones do this for portrait photos): the decoder + (stb_image) ignores the tag. False without Pillow, or when the tag is missing, 1 or unreadable (#1229).""" + try: + import io + from PIL import Image + with Image.open(io.BytesIO(data)) as im: + return im.getexif().get(0x0112, 1) not in (None, 0, 1) + except Exception: # noqa: BLE001 - any failure leaves the image as it was sent + return False + @staticmethod def normalize(data: bytes) -> bytes: - """The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG.""" - if data[:3] == b"\xff\xd8\xff" or data[:8] == b"\x89PNG\r\n\x1a\n" or data[:2] == b"BM" or \ + """The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG. + A JPEG with an EXIF Orientation other than 1 is turned upright first (needs Pillow).""" + jpeg = data[:3] == b"\xff\xd8\xff" + if (jpeg and not Vision._exif_rotated(data)) or data[:8] == b"\x89PNG\r\n\x1a\n" or data[:2] == b"BM" or \ data[:6] in (b"GIF87a", b"GIF89a"): return data try: @@ -1768,6 +1782,8 @@ class Vision: try: im = Image.open(io.BytesIO(data)) im.load() + from PIL import ImageOps + im = ImageOps.exif_transpose(im) # the camera's orientation tag, applied (#1229) except Exception as e: raise ValueError(f"the image could not be read ({e})") from None if im.mode in ("RGBA", "LA", "P") and "transparency" in im.info or im.mode in ("RGBA", "LA"): diff --git a/serve/test_exif_orientation.py b/serve/test_exif_orientation.py new file mode 100644 index 00000000..5eafa0ae --- /dev/null +++ b/serve/test_exif_orientation.py @@ -0,0 +1,47 @@ +"""#1229: a phone JPEG stored turned (EXIF Orientation 6 or 8) is turned upright before the vision encoder reads it.""" +import io +import unittest + +from serve.server import Vision + +try: + from PIL import Image +except ImportError: # Pillow is optional: the image then goes through as it was + Image = None + + +def jpeg(size, orientation=None) -> bytes: + im = Image.new("RGB", size, (200, 30, 30)) + exif = Image.Exif() + if orientation is not None: + exif[0x0112] = orientation + out = io.BytesIO() + im.save(out, format="JPEG", exif=exif) + return out.getvalue() + + +@unittest.skipIf(Image is None, "Pillow is not installed") +class ExifOrientation(unittest.TestCase): + def test_a_turned_jpeg_comes_out_upright_as_a_png(self): + for tag in (6, 8): + out = Vision.normalize(jpeg((40, 20), tag)) + self.assertEqual(out[:8], b"\x89PNG\r\n\x1a\n") + self.assertEqual(Image.open(io.BytesIO(out)).size, (20, 40)) + + def test_a_jpeg_without_the_tag_or_with_tag_1_passes_through_unchanged(self): + for tag in (None, 1): + data = jpeg((40, 20), tag) + self.assertIs(Vision.normalize(data), data) + + def test_png_passes_through(self): + out = io.BytesIO() + Image.new("RGB", (4, 4)).save(out, format="PNG") + self.assertEqual(Vision.normalize(out.getvalue()), out.getvalue()) + + def test_a_broken_jpeg_is_left_as_it_was_sent(self): + data = b"\xff\xd8\xff" + b"not a jpeg" + self.assertEqual(Vision.normalize(data), data) + + +if __name__ == "__main__": + unittest.main()