diff --git a/PIL/JpegImagePlugin.py b/PIL/JpegImagePlugin.py index ae420551b..22ac2eaba 100644 --- a/PIL/JpegImagePlugin.py +++ b/PIL/JpegImagePlugin.py @@ -119,8 +119,17 @@ def APP(self, marker): # If DPI isn't in JPEG header, fetch from EXIF if "dpi" not in self.info and "exif" in self.info: - x_resolution = self._getexif()[0x011A] - self.info["dpi"] = x_resolution[0] / x_resolution[1] + exif = self._getexif() + try: + resolution_unit = exif[0x0128] + x_resolution = exif[0x011A] + dpi = x_resolution[0] / x_resolution[1] + if resolution_unit == 3: # cm + # 1 dpcm = 2.54 dpi + dpi *= 2.54 + self.info["dpi"] = dpi, dpi + except KeyError: + self.info["dpi"] = 72, 72 def COM(self, marker): diff --git a/Tests/images/exif-200dpcm.jpg b/Tests/images/exif-200dpcm.jpg new file mode 100644 index 000000000..efa55613b Binary files /dev/null and b/Tests/images/exif-200dpcm.jpg differ diff --git a/Tests/images/no-dpi-in-exif.jpg b/Tests/images/no-dpi-in-exif.jpg new file mode 100644 index 000000000..9a4731a5b Binary files /dev/null and b/Tests/images/no-dpi-in-exif.jpg differ diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py index f543119f6..21436edc1 100644 --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -506,7 +506,27 @@ class TestFileJpeg(PillowTestCase): im = Image.open("Tests/images/photoshop-200dpi.jpg") # Act / Assert - self.assertEqual(im.info.get("dpi"), 200) + self.assertEqual(im.info.get("dpi"), (200, 200)) + + def test_dpi_from_dpcm_exif(self): + # Arrange + # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm: + # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg + im = Image.open("Tests/images/exif-200dpcm.jpg") + + # Act / Assert + self.assertEqual(im.info.get("dpi"), (508, 508)) + + def test_no_dpi_in_exif(self): + # Arrange + # This is photoshop-200dpi.jpg with resolution removed from EXIF: + # exiftool "-*resolution*"= photoshop-200dpi.jpg + im = Image.open("Tests/images/no-dpi-in-exif.jpg") + + # Act / Assert + # "When the image resolution is unknown, 72 [dpi] is designated." + # http://www.exiv2.org/tags.html + self.assertEqual(im.info.get("dpi"), (72, 72)) if __name__ == '__main__':