repo
string
pull_number
int64
instance_id
string
issue_numbers
sequence
base_commit
string
patch
string
test_patch
string
problem_statement
string
hints_text
string
created_at
timestamp[ns, tz=UTC]
version
float64
python-pillow/Pillow
7,870
python-pillow__Pillow-7870
[ "7511" ]
8afedb7ba441933a5c1948b649585cff0921ec20
diff --git a/src/PIL/Jpeg2KImagePlugin.py b/src/PIL/Jpeg2KImagePlugin.py --- a/src/PIL/Jpeg2KImagePlugin.py +++ b/src/PIL/Jpeg2KImagePlugin.py @@ -19,7 +19,7 @@ import os import struct -from . import Image, ImageFile, _binary +from . import Image, ImageFile, ImagePalette, _binary class BoxReader: @@ -162,6 +162,7 @@ def _parse_jp2_header(fp): bpc = None nc = None dpi = None # 2-tuple of DPI info, or None + palette = None while header.has_next_box(): tbox = header.next_box_type() @@ -179,6 +180,14 @@ def _parse_jp2_header(fp): mode = "RGB" elif nc == 4: mode = "RGBA" + elif tbox == b"pclr" and mode in ("L", "LA"): + ne, npc = header.read_fields(">HB") + bitdepths = header.read_fields(">" + ("B" * npc)) + if max(bitdepths) <= 8: + palette = ImagePalette.ImagePalette() + for i in range(ne): + palette.getcolor(header.read_fields(">" + ("B" * npc))) + mode = "P" if mode == "L" else "PA" elif tbox == b"res ": res = header.read_boxes() while res.has_next_box(): @@ -195,7 +204,7 @@ def _parse_jp2_header(fp): msg = "Malformed JP2 header" raise SyntaxError(msg) - return size, mode, mimetype, dpi + return size, mode, mimetype, dpi, palette ## @@ -217,7 +226,7 @@ def _open(self): if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a": self.codec = "jp2" header = _parse_jp2_header(self.fp) - self._size, self._mode, self.custom_mimetype, dpi = header + self._size, self._mode, self.custom_mimetype, dpi, self.palette = header if dpi is not None: self.info["dpi"] = dpi if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"):
diff --git a/Tests/test_file_jpeg2k.py b/Tests/test_file_jpeg2k.py --- a/Tests/test_file_jpeg2k.py +++ b/Tests/test_file_jpeg2k.py @@ -364,6 +364,16 @@ def test_subsampling_decode(name: str) -> None: assert_image_similar(im, expected, epsilon) +@pytest.mark.skipif( + not os.path.exists(EXTRA_DIR), reason="Extra image files not installed" +) +def test_pclr() -> None: + with Image.open(f"{EXTRA_DIR}/issue104_jpxstream.jp2") as im: + assert im.mode == "P" + assert len(im.palette.colors) == 256 + assert im.palette.colors[(255, 255, 255)] == 0 + + def test_comment() -> None: with Image.open("Tests/images/comment.jp2") as im: assert im.info["comment"] == b"Created by OpenJPEG version 2.5.0"
JPEG2000 image read incorrectly When doing ```python from PIL import Image Image.open('test.jp2').show() ``` on the file [test.jp2.zip](https://github.com/python-pillow/Pillow/files/13223024/test.jp2.zip) an apparently incorrect result is displayed. I have checked this with both the latest Pillow-10.1.0 as well as my reference Pillow-9.4.0: both results are identical and both are incorrect.
Am I correct in saying that you created this image <img src="https://github.com/python-pillow/Pillow/assets/3112309/71af2f2b-79e6-4dcf-869e-421a1433e4af" width="400" /> but were expecting this? <img src="https://github.com/python-pillow/Pillow/assets/3112309/963488af-1728-4f6a-b588-4e76ef846107" width="400" /> I see there is a "pclr" box in the image. It looks like an RGB palette that we're not handling yet. Is the image you attached one that can be added a test image, and distributed under Pillow's license? I vaguely remember that I got this image from some student lecture notes that were freely distributed on the web. That is to say, I am not the author of this image. It seems to me that https://github.com/uclouvain/openjpeg/pull/1463 is relevant, and we might have an easier time addressing this once the next version of OpenJPEG is released. It turns out that https://github.com/uclouvain/openjpeg/pull/1463 didn't help. I've created https://github.com/python-pillow/Pillow/pull/7867 to resolve this.
2024-03-12T00:48:03Z
10.2
python-pillow/Pillow
7,823
python-pillow__Pillow-7823
[ "7817" ]
bebf038e49b10500a36161c1bac24b76cf70bcd4
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -392,8 +392,8 @@ def chunk_iCCP(self, pos, length): # Compressed profile n bytes (zlib with deflate compression) i = s.find(b"\0") logger.debug("iCCP profile name %r", s[:i]) - logger.debug("Compression method %s", s[i]) - comp_method = s[i] + comp_method = s[i + 1] + logger.debug("Compression method %s", comp_method) if comp_method != 0: msg = f"Unknown compression method {comp_method} in iCCP chunk" raise SyntaxError(msg)
diff --git a/Tests/images/unknown_compression_method.png b/Tests/images/unknown_compression_method.png new file mode 100644 Binary files /dev/null and b/Tests/images/unknown_compression_method.png differ diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -619,6 +619,10 @@ def test_textual_chunks_after_idat(self) -> None: with Image.open("Tests/images/hopper_idat_after_image_end.png") as im: assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"} + def test_unknown_compression_method(self) -> None: + with pytest.raises(SyntaxError, match="Unknown compression method"): + PngImagePlugin.PngImageFile("Tests/images/unknown_compression_method.png") + def test_padded_idat(self) -> None: # This image has been manually hexedited # so that the IDAT chunk has padding at the end
PNG iCCP chunk profile compression type verification seems wrong ### What did you do? Hello, I've been looking around at some PNG decoders and I think I've found a small bug in your iCCP chunk handling. ### What did you expect to happen? I would expect the library to read the iCCP chunk compression version byte correctly. ### What actually happened? This library incorrectly assumes that the NUL terminator is the compression byte. This does not cause issues in practice, since the compression byte should currently always be 0, but I thought I'd report this anyways. ### What are your OS, Python and Pillow versions? * OS: Windows * Python: Python 3.11.8-1 (MSYS2) * Pillow: 10.2.0-1 (MSYS2) ```python from PIL import Image, ImageFile import logging logging.basicConfig(level=logging.DEBUG) path = 'ArcTriomphe-iCCP-red-green-swap-mod.png' with Image.open(path) as img: icc = img.info.get('icc_profile') print(icc) print(img) ``` Here are my 2 test files: ![ArcTriomphe-iCCP-red-green-swap](https://github.com/python-pillow/Pillow/assets/80441888/792cedba-3ab1-4d46-bfb9-87389e8337f7) ![ArcTriomphe-iCCP-red-green-swap-mod](https://github.com/python-pillow/Pillow/assets/80441888/65141037-59cf-4381-94d7-0d18824b0096) The first one is a normal image with an embedded icc profile. The second is the same image, modified in a hex editor to change the compression version field from 0 to 1. Here is the output from the first image: ``` DEBUG:PIL.PngImagePlugin:STREAM b'IHDR' 16 13 DEBUG:PIL.PngImagePlugin:STREAM b'iCCP' 41 460 DEBUG:PIL.PngImagePlugin:iCCP profile name b'Swapped red & green channel' DEBUG:PIL.PngImagePlugin:Compression method 0 DEBUG:PIL.PngImagePlugin:STREAM b'PLTE' 513 759 DEBUG:PIL.PngImagePlugin:STREAM b'IDAT' 1284 3618 b'\x00\x00\x02\x84lcms\x02@\x00\x00mntrRGB XYZ \x07\xd5\x00\x08\x00\r\x00\x16\x00!\x00,acspSUNW\x00\x00\x00\x00none\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf6\xd6\x00\x01\x00\x00\x00\x00\xd3-Greg^\xdf\x16\x9a"\xbb\xfd\xab\xb6@n\xf998\rz\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ndesc\x00\x00\x00\xfc\x00\x00\x00\x84cprt\x00\x00\x01\x80\x00\x00\x00\x90wtpt\x00\x00\x02\x10\x00\x00\x00\x14bkpt\x00\x00\x02$\x00\x00\x00\x14rXYZ\x00\x00\x028\x00\x00\x00\x14gXYZ\x00\x00\x02L\x00\x00\x00\x14bXYZ\x00\x00\x02`\x00\x00\x00\x14rTRC\x00\x00\x02t\x00\x00\x00\x0egTRC\x00\x00\x02t\x00\x00\x00\x0ebTRC\x00\x00\x02t\x00\x00\x00\x0edesc\x00\x00\x00\x00\x00\x00\x00\'"sGRB": red and green channels swapped\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0067 bytes of wasted space, courtesy of Apple Computer, dum de dum.\x00\x00text\x00\x00\x00\x00Copyright 2005 Greg Roelofs. Licensed under Creative Commons Attribution-NonCommercial, http://creativecommons.org/licenses/by-nc/2.5/ \x00XYZ \x00\x00\x00\x00\x00\x00\xf3Q\x00\x01\x00\x00\x00\x01\x16\xccXYZ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00XYZ \x00\x00\x00\x00\x00\x00b\x98\x00\x00\xb7\x86\x00\x00\x18\xdaXYZ \x00\x00\x00\x00\x00\x00o\xa1\x00\x008\xf5\x00\x00\x03\x90XYZ \x00\x00\x00\x00\x00\x00$\xa0\x00\x00\x0f\x84\x00\x00\xb6\xc9curv\x00\x00\x00\x00\x00\x00\x00\x01\x023\x00\x00' <PIL.PngImagePlugin.PngImageFile image mode=P size=64x64 at 0x26C30640E10> ``` Here is the output from the second image: ``` DEBUG:PIL.PngImagePlugin:STREAM b'IHDR' 16 13 DEBUG:PIL.PngImagePlugin:STREAM b'iCCP' 41 460 DEBUG:PIL.PngImagePlugin:iCCP profile name b'Swapped red & green channel' DEBUG:PIL.PngImagePlugin:Compression method 0 DEBUG:PIL.Image:Importing BlpImagePlugin DEBUG:PIL.Image:Importing BmpImagePlugin DEBUG:PIL.Image:Importing BufrStubImagePlugin DEBUG:PIL.Image:Importing CurImagePlugin DEBUG:PIL.Image:Importing DcxImagePlugin DEBUG:PIL.Image:Importing DdsImagePlugin DEBUG:PIL.Image:Importing EpsImagePlugin DEBUG:PIL.Image:Importing FitsImagePlugin DEBUG:PIL.Image:Importing FliImagePlugin DEBUG:PIL.Image:Importing FpxImagePlugin DEBUG:PIL.Image:Image: failed to import FpxImagePlugin: No module named 'olefile' DEBUG:PIL.Image:Importing FtexImagePlugin DEBUG:PIL.Image:Importing GbrImagePlugin DEBUG:PIL.Image:Importing GifImagePlugin DEBUG:PIL.Image:Importing GribStubImagePlugin DEBUG:PIL.Image:Importing Hdf5StubImagePlugin DEBUG:PIL.Image:Importing IcnsImagePlugin DEBUG:PIL.Image:Importing IcoImagePlugin DEBUG:PIL.Image:Importing ImImagePlugin DEBUG:PIL.Image:Importing ImtImagePlugin DEBUG:PIL.Image:Importing IptcImagePlugin DEBUG:PIL.Image:Importing JpegImagePlugin DEBUG:PIL.Image:Importing Jpeg2KImagePlugin DEBUG:PIL.Image:Importing McIdasImagePlugin DEBUG:PIL.Image:Importing MicImagePlugin DEBUG:PIL.Image:Image: failed to import MicImagePlugin: No module named 'olefile' DEBUG:PIL.Image:Importing MpegImagePlugin DEBUG:PIL.Image:Importing MpoImagePlugin DEBUG:PIL.Image:Importing MspImagePlugin DEBUG:PIL.Image:Importing PalmImagePlugin DEBUG:PIL.Image:Importing PcdImagePlugin DEBUG:PIL.Image:Importing PcxImagePlugin DEBUG:PIL.Image:Importing PdfImagePlugin DEBUG:PIL.Image:Importing PixarImagePlugin DEBUG:PIL.Image:Importing PngImagePlugin DEBUG:PIL.Image:Importing PpmImagePlugin DEBUG:PIL.Image:Importing PsdImagePlugin DEBUG:PIL.Image:Importing QoiImagePlugin DEBUG:PIL.Image:Importing SgiImagePlugin DEBUG:PIL.Image:Importing SpiderImagePlugin DEBUG:PIL.Image:Importing SunImagePlugin DEBUG:PIL.Image:Importing TgaImagePlugin DEBUG:PIL.Image:Importing TiffImagePlugin DEBUG:PIL.Image:Importing WebPImagePlugin DEBUG:PIL.Image:Importing WmfImagePlugin DEBUG:PIL.Image:Importing XbmImagePlugin DEBUG:PIL.Image:Importing XpmImagePlugin DEBUG:PIL.Image:Importing XVThumbImagePlugin <traceback omitted> PIL.UnidentifiedImageError: cannot identify image file 'ArcTriomphe-iCCP-red-green-swap-mod.png' ``` As can be seen, PIL thinks the compression byte never changes. The issue is [here](https://github.com/python-pillow/Pillow/blob/380bc1766b7a3c23bde679be307ddfec1df252d0/src/PIL/PngImagePlugin.py#L395-L396), where there is an off-by-one error. `s[i]` should be `s[i + 1]` for the compression byte.
2024-02-22T08:58:17Z
10.2
python-pillow/Pillow
7,883
python-pillow__Pillow-7883
[ "7876" ]
794a7d691fcc70ffd3f6dad58737cc1ad2b8da26
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -1166,6 +1166,9 @@ def _seek(self, frame): self.__next, self.fp.tell(), ) + if self.__next >= 2**63: + msg = "Unable to seek to frame" + raise ValueError(msg) self.fp.seek(self.__next) self._frame_pos.append(self.__next) logger.debug("Loading tags, location: %s", self.fp.tell())
diff --git a/Tests/images/seek_too_large.tif b/Tests/images/seek_too_large.tif new file mode 100644 Binary files /dev/null and b/Tests/images/seek_too_large.tif differ diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -113,6 +113,10 @@ def test_bigtiff(self, tmp_path: Path) -> None: outfile = str(tmp_path / "temp.tif") im.save(outfile, save_all=True, append_images=[im], tiffinfo=im.tag_v2) + def test_seek_too_large(self): + with pytest.raises(ValueError, match="Unable to seek to frame"): + Image.open("Tests/images/seek_too_large.tif") + def test_set_legacy_api(self) -> None: ifd = TiffImagePlugin.ImageFileDirectory_v2() with pytest.raises(Exception) as e:
Uncaught Exception(s) in Pillow Library ### What did you do? We (@DogukanK, @esraercann) discovered a 3 crashes in Python Pillow library because of 'Uncaught Exception' via specially crafted input. ### What did you expect to happen? Exceptions should be handled properly in Pillow. ### What actually happened? Crash. * Here is the first crash log: ```bash === Uncaught Python exception: === error: argument out of range Traceback (most recent call last): File "/home/ubuntu/targets/pillow/main.py", line 20, in TestOneInput pilfuzz(data) File "/home/ubuntu/targets/pillow/main.py", line 11, in pilfuzz out = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 2807, in transpose def transpose(self, method): File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/ImageFile.py", line 266, in load err_code = decoder.decode(b"")[1] File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/PpmImagePlugin.py", line 273, in decode data = self._decode_blocks(maxval) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/PpmImagePlugin.py", line 261, in _decode_blocks data += o32(value) if self.mode == "I" else o8(value) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/_binary.py", line 93, in o32le def o32le(i: int) -> bytes: error: argument out of range ``` Poc: ```python3 >>> from PIL import Image >>> im = Image.open("./crash-4148ce4324e2e54cc3c2c6aa369420ddbd9dee5e") >>> im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 2818, in transpose self.load() File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/ImageFile.py", line 266, in load err_code = decoder.decode(b"")[1] File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/PpmImagePlugin.py", line 273, in decode data = self._decode_blocks(maxval) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/PpmImagePlugin.py", line 261, in _decode_blocks data += o32(value) if self.mode == "I" else o8(value) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/_binary.py", line 94, in o32le return pack("<I", i) struct.error: argument out of range ``` * Here is the second crash: ```python3 >>> from PIL import Image, ImageFilter >>> im = Image.open("./crash-73c3d4dca546775e83ea511a0fc882f3c5b6f60a") >>> im.filter(ImageFilter.DETAIL) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 1281, in filter self.load() File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/GbrImagePlugin.py", line 94, in load self.frombytes(self.fp.read(self._data_size)) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 810, in frombytes d.setimage([self.im](http://self.im/)) MemoryError ``` * Here is the third crash: ```bash === Uncaught Python exception: === OverflowError: Python int too large to convert to C ssize_t Traceback (most recent call last): File "/home/ubuntu/targets/pillow/main.py", line 16, in TestOneInput pilfuzz(data) File "/home/ubuntu/targets/pillow/main.py", line 10, in pilfuzz with Image.open(io.BytesIO(data)) as im: File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 3258, in open preinit() File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 3273, in _open_core fp.seek(0) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/TiffImagePlugin.py", line 1082, in __init__ super().__init__(fp, filename) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/ImageFile.py", line 137, in __init__ self._open() File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/TiffImagePlugin.py", line 1109, in _open self._seek(0) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/TiffImagePlugin.py", line 1150, in _seek self.fp.seek(self.__next) OverflowError: Python int too large to convert to C ssize_t ``` PoC: ```python3 Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from PIL import Image >>> im = Image.open("./crash-ecd6f7d1583338a2a2c4aaee944b0b3371f4f926") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 3293, in open im = _open_core( File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 3274, in _open_core im = factory(fp, filename) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/TiffImagePlugin.py", line 1082, in __init__ super().__init__(fp, filename) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/ImageFile.py", line 137, in __init__ self._open() File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/TiffImagePlugin.py", line 1109, in _open self._seek(0) File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/TiffImagePlugin.py", line 1150, in _seek self.fp.seek(self.__next) ValueError: cannot fit 'int' into an offset-sized integer ``` ### What are your OS, Python and Pillow versions? * Python3 Version: Python 3.10.12 * PIL Version: 10.2.0 * OS: Ubuntu 22.04.3 LTS 5.15.0-84-generic x86/64 ### Crash Files [Archive.zip](https://github.com/python-pillow/Pillow/files/14588492/Archive.zip)
Looking at your second situation, I see it is hitting https://github.com/python-pillow/Pillow/blob/9e3d1a7b05b5c961eb1daaae4e5ed62feb6d5507/src/decode.c#L194-L198 You are trying to create an image that is 134,217,792px wide, greater than the limit in that logic of 67,108,856px wide. So that's not an unexpected exception, that's something we're deliberately raising. The first one was sent to security@. The error for that one is raised by python core, and isn't an issue unless valgrind finds memory corruption, and since that's directly in python core, it would be a bug for them.
2024-03-16T02:44:11Z
10.2
python-pillow/Pillow
7,496
python-pillow__Pillow-7496
[ "7495" ]
d05ff5059f2bb9a46c512f8d303e8e3f8cc6939e
diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py --- a/src/PIL/JpegImagePlugin.py +++ b/src/PIL/JpegImagePlugin.py @@ -85,10 +85,12 @@ def APP(self, marker): self.info["dpi"] = jfif_density self.info["jfif_unit"] = jfif_unit self.info["jfif_density"] = jfif_density - elif marker == 0xFFE1 and s[:5] == b"Exif\0": - if "exif" not in self.info: - # extract EXIF information (incomplete) - self.info["exif"] = s # FIXME: value will change + elif marker == 0xFFE1 and s[:6] == b"Exif\0\0": + # extract EXIF information + if "exif" in self.info: + self.info["exif"] += s[6:] + else: + self.info["exif"] = s self._exif_offset = self.fp.tell() - n + 6 elif marker == 0xFFE2 and s[:5] == b"FPXR\0": # extract FlashPix information (incomplete)
diff --git a/Tests/images/multiple_exif.jpg b/Tests/images/multiple_exif.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/multiple_exif.jpg differ diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -822,6 +822,10 @@ def test_ifd_offset_exif(self): # Act / Assert assert im._getexif()[306] == "2017:03:13 23:03:09" + def test_multiple_exif(self): + with Image.open("Tests/images/multiple_exif.jpg") as im: + assert im.info["exif"] == b"Exif\x00\x00firstsecond" + @mark_if_feature_version( pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing" )
Multi-segment Exif fails to read ### What did you do? Writing code to read ai generated images and tried to get User Comment field from EXIF data contained in an image opened with Image.open. The jpeg image is as far as I can tell not corrupt. ExifTool reads it OK and shows me the comment with a minor warning that "File contains multi-segment EXIF." I can see the User Comment listed in the console with ExifTool. It's large, but looks OK. ### What did you expect to happen? User Comment field to be read and returned. ### What actually happened? Using image.getexif().get_ifd(ExifTags.IFD.Exif) returns an empty dict along with this warning on the console- python3.11/site-packages/PIL/TiffImagePlugin.py:868: UserWarning: Truncated File Read ### What are your OS, Python and Pillow versions? * OS: Linux pop-os 6.2.6-76060206-generic (Ubuntu compatible with 22 I think) * Python: 3.11 * Pillow: 10.1.0 ```python with Image.open("03d2695a.jpeg") as i: x = i.getexif().get_ifd(ExifTags.IFD.Exif) ``` [03d2695a.jpeg.zip](https://github.com/python-pillow/Pillow/files/13166523/03d2695a.jpeg.zip)
2023-10-26T10:52:20Z
10.1
python-pillow/Pillow
7,481
python-pillow__Pillow-7481
[ "7479" ]
a10dec01b5a3f63c43f7095dbc7aec5658aad251
diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -230,21 +230,21 @@ def _bitmap(self, header=0, offset=0): else: padding = file_info["palette_padding"] palette = read(padding * file_info["colors"]) - greyscale = True + grayscale = True indices = ( (0, 255) if file_info["colors"] == 2 else list(range(file_info["colors"])) ) - # ----------------- Check if greyscale and ignore palette if so + # ----------------- Check if grayscale and ignore palette if so for ind, val in enumerate(indices): rgb = palette[ind * padding : ind * padding + 3] if rgb != o8(val) * 3: - greyscale = False + grayscale = False - # ------- If all colors are grey, white or black, ditch palette - if greyscale: + # ------- If all colors are gray, white or black, ditch palette + if grayscale: self._mode = "1" if file_info["colors"] == 2 else "L" raw_mode = self.mode else: diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -878,12 +878,12 @@ def convert( "L", "RGB" and "CMYK". The ``matrix`` argument only supports "L" and "RGB". - When translating a color image to greyscale (mode "L"), + When translating a color image to grayscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 - The default method of converting a greyscale ("L") or "RGB" + The default method of converting a grayscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is ``None``, all values larger than 127 are set to 255 (white), @@ -1238,7 +1238,7 @@ def draft(self, mode, size): Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color - JPEG to greyscale while loading it. + JPEG to grayscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. @@ -1610,13 +1610,13 @@ def histogram(self, mask=None, extrema=None): than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). - A bilevel image (mode "1") is treated as a greyscale ("L") image + A bilevel image (mode "1") is treated as a grayscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a - bi-level image (mode "1") or a greyscale image ("L"). + bi-level image (mode "1") or a grayscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. @@ -1636,13 +1636,13 @@ def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. - A bilevel image (mode "1") is treated as a greyscale ("L") + A bilevel image (mode "1") is treated as a grayscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be - either a bi-level image (mode "1") or a greyscale image ("L"). + either a bi-level image (mode "1") or a grayscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. @@ -2876,7 +2876,7 @@ class ImageTransformHandler: def _wedge(): - """Create greyscale wedge (for debugging only)""" + """Create grayscale wedge (for debugging only)""" return Image()._new(core.wedge("L")) diff --git a/src/PIL/ImageChops.py b/src/PIL/ImageChops.py --- a/src/PIL/ImageChops.py +++ b/src/PIL/ImageChops.py @@ -19,7 +19,7 @@ def constant(image, value): - """Fill a channel with a given grey level. + """Fill a channel with a given gray level. :rtype: :py:class:`~PIL.Image.Image` """ diff --git a/src/PIL/ImageColor.py b/src/PIL/ImageColor.py --- a/src/PIL/ImageColor.py +++ b/src/PIL/ImageColor.py @@ -124,7 +124,7 @@ def getcolor(color, mode): """ Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is - not color or a palette image, converts the RGB value to a greyscale value. + not color or a palette image, converts the RGB value to a grayscale value. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. diff --git a/src/PIL/ImageEnhance.py b/src/PIL/ImageEnhance.py --- a/src/PIL/ImageEnhance.py +++ b/src/PIL/ImageEnhance.py @@ -59,7 +59,7 @@ class Contrast(_Enhance): This class can be used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 - gives a solid grey image. A factor of 1.0 gives the original image. + gives a solid gray image. A factor of 1.0 gives the original image. """ def __init__(self, image): diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -593,7 +593,7 @@ def solarize(image, threshold=128): Invert all pixel values above a threshold. :param image: The image to solarize. - :param threshold: All pixels above this greyscale level are inverted. + :param threshold: All pixels above this grayscale level are inverted. :return: An image. """ lut = [] diff --git a/src/PIL/ImageWin.py b/src/PIL/ImageWin.py --- a/src/PIL/ImageWin.py +++ b/src/PIL/ImageWin.py @@ -54,9 +54,9 @@ class Dib: "L", "P", or "RGB". If the display requires a palette, this constructor creates a suitable - palette and associates it with the image. For an "L" image, 128 greylevels + palette and associates it with the image. For an "L" image, 128 graylevels are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together - with 20 greylevels. + with 20 graylevels. To make sure that palettes work properly under Windows, you must call the ``palette`` method upon certain events from Windows. diff --git a/src/PIL/PSDraw.py b/src/PIL/PSDraw.py --- a/src/PIL/PSDraw.py +++ b/src/PIL/PSDraw.py @@ -109,7 +109,7 @@ def image(self, box, im, dpi=None): if im.mode == "1": dpi = 200 # fax else: - dpi = 100 # greyscale + dpi = 100 # grayscale # image size (on paper) x = im.size[0] * 72 / dpi y = im.size[1] * 72 / dpi diff --git a/src/PIL/PalmImagePlugin.py b/src/PIL/PalmImagePlugin.py --- a/src/PIL/PalmImagePlugin.py +++ b/src/PIL/PalmImagePlugin.py @@ -124,7 +124,7 @@ def _save(im, fp, filename): if im.encoderinfo.get("bpp") in (1, 2, 4): # this is 8-bit grayscale, so we shift it to get the high-order bits, # and invert it because - # Palm does greyscale from white (0) to black (1) + # Palm does grayscale from white (0) to black (1) bpp = im.encoderinfo["bpp"] im = im.point( lambda x, shift=8 - bpp, maxval=(1 << bpp) - 1: maxval - (x >> shift) diff --git a/src/PIL/PcxImagePlugin.py b/src/PIL/PcxImagePlugin.py --- a/src/PIL/PcxImagePlugin.py +++ b/src/PIL/PcxImagePlugin.py @@ -91,7 +91,7 @@ def _open(self): self.fp.seek(-769, io.SEEK_END) s = self.fp.read(769) if len(s) == 769 and s[0] == 12: - # check if the palette is linear greyscale + # check if the palette is linear grayscale for i in range(256): if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: mode = rawmode = "P" @@ -203,7 +203,7 @@ def _save(im, fp, filename): palette += b"\x00" * (768 - len(palette)) fp.write(palette) # 768 bytes elif im.mode == "L": - # greyscale palette + # grayscale palette fp.write(o8(12)) for i in range(256): fp.write(o8(i) * 3) diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -56,7 +56,7 @@ _MODES = { # supported bits/color combinations, and corresponding modes/rawmodes - # Greyscale + # Grayscale (1, 0): ("1", "1"), (2, 0): ("L", "L;2"), (4, 0): ("L", "L;4"), @@ -70,7 +70,7 @@ (2, 3): ("P", "P;2"), (4, 3): ("P", "P;4"), (8, 3): ("P", "P"), - # Greyscale with alpha + # Grayscale with alpha (8, 4): ("LA", "LA"), (16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available # Truecolour with alpha
diff --git a/Tests/images/apng/mode_greyscale.png b/Tests/images/apng/mode_grayscale.png similarity index 100% rename from Tests/images/apng/mode_greyscale.png rename to Tests/images/apng/mode_grayscale.png diff --git a/Tests/images/apng/mode_greyscale_alpha.png b/Tests/images/apng/mode_grayscale_alpha.png similarity index 100% rename from Tests/images/apng/mode_greyscale_alpha.png rename to Tests/images/apng/mode_grayscale_alpha.png diff --git a/Tests/images/hopper_rle8_greyscale.bmp b/Tests/images/hopper_rle8_grayscale.bmp similarity index 100% rename from Tests/images/hopper_rle8_greyscale.bmp rename to Tests/images/hopper_rle8_grayscale.bmp diff --git a/Tests/test_file_apng.py b/Tests/test_file_apng.py --- a/Tests/test_file_apng.py +++ b/Tests/test_file_apng.py @@ -231,13 +231,13 @@ def test_apng_mode(): assert im.getpixel((0, 0)) == (0, 0, 128, 191) assert im.getpixel((64, 32)) == (0, 0, 128, 191) - with Image.open("Tests/images/apng/mode_greyscale.png") as im: + with Image.open("Tests/images/apng/mode_grayscale.png") as im: assert im.mode == "L" im.seek(im.n_frames - 1) assert im.getpixel((0, 0)) == 128 assert im.getpixel((64, 32)) == 255 - with Image.open("Tests/images/apng/mode_greyscale_alpha.png") as im: + with Image.open("Tests/images/apng/mode_grayscale_alpha.png") as im: assert im.mode == "LA" im.seek(im.n_frames - 1) assert im.getpixel((0, 0)) == (128, 191) diff --git a/Tests/test_file_bmp.py b/Tests/test_file_bmp.py --- a/Tests/test_file_bmp.py +++ b/Tests/test_file_bmp.py @@ -159,7 +159,7 @@ def test_rle8(): with Image.open("Tests/images/hopper_rle8.bmp") as im: assert_image_similar_tofile(im.convert("RGB"), "Tests/images/hopper.bmp", 12) - with Image.open("Tests/images/hopper_rle8_greyscale.bmp") as im: + with Image.open("Tests/images/hopper_rle8_grayscale.bmp") as im: assert_image_equal_tofile(im, "Tests/images/bw_gradient.png") # This test image has been manually hexedited diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -590,7 +590,7 @@ def test_save_dispose(tmp_path): def test_dispose2_palette(tmp_path): out = str(tmp_path / "temp.gif") - # Four colors: white, grey, black, red + # Four colors: white, gray, black, red circles = [(255, 255, 255), (153, 153, 153), (0, 0, 0), (255, 0, 0)] im_list = [] diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -297,7 +297,7 @@ def test_save_p_transparent_black(self, tmp_path): assert_image(im, "RGBA", (10, 10)) assert im.getcolors() == [(100, (0, 0, 0, 0))] - def test_save_greyscale_transparency(self, tmp_path): + def test_save_grayscale_transparency(self, tmp_path): for mode, num_transparent in {"1": 1994, "L": 559, "I": 559}.items(): in_file = "Tests/images/" + mode.lower() + "_trns.png" with Image.open(in_file) as im: diff --git a/Tests/test_imagechops.py b/Tests/test_imagechops.py --- a/Tests/test_imagechops.py +++ b/Tests/test_imagechops.py @@ -10,7 +10,7 @@ ORANGE = (255, 128, 0) WHITE = (255, 255, 255) -GREY = 128 +GRAY = 128 def test_sanity(): @@ -121,12 +121,12 @@ def test_constant(): im = Image.new("RGB", (20, 10)) # Act - new = ImageChops.constant(im, GREY) + new = ImageChops.constant(im, GRAY) # Assert assert new.size == im.size - assert new.getpixel((0, 0)) == GREY - assert new.getpixel((19, 9)) == GREY + assert new.getpixel((0, 0)) == GRAY + assert new.getpixel((19, 9)) == GRAY def test_darker_image(): diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -303,8 +303,8 @@ def test_multiline_spacing(font): "orientation", (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270) ) def test_rotated_transposed_font(font, orientation): - img_grey = Image.new("L", (100, 100)) - draw = ImageDraw.Draw(img_grey) + img_gray = Image.new("L", (100, 100)) + draw = ImageDraw.Draw(img_gray) word = "testing" transposed_font = ImageFont.TransposedFont(font, orientation=orientation) @@ -344,8 +344,8 @@ def test_rotated_transposed_font(font, orientation): ), ) def test_unrotated_transposed_font(font, orientation): - img_grey = Image.new("L", (100, 100)) - draw = ImageDraw.Draw(img_grey) + img_gray = Image.new("L", (100, 100)) + draw = ImageDraw.Draw(img_gray) word = "testing" transposed_font = ImageFont.TransposedFont(font, orientation=orientation)
Mix use of grayscale/greyscale in document and code <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? I've been searching in the document and found it use "grayscale" in some places and "greyscale" in some other places, describing same type of images in Pillow. I also viewed those parts of code and found out they are mostly consistent with corresponding documents. ### What did you expect to happen? It should be using the same word across the whole document and code. ### What actually happened? Mix use of slightly different spelling words across multiple places. ### What are your OS, Python and Pillow versions? Not related to the issue. The mix use of both words seems to have been the case for a very long time, at least since Pillow 3.x, which makes me a bit confused. ### Examples #### Examples of grayscale: * `L` (8-bit pixels, grayscale) [[Modes](https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes)] * GIF files are initially read as grayscale (L) or palette mode (P) images. [[GIF](https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif)] * [[`PIL.ImageOps.grayscale(image)`](https://pillow.readthedocs.io/en/stable/reference/ImageOps.html#PIL.ImageOps.grayscale)] #### Examples of greyscale: * When translating a color image to greyscale (mode “L”) [[`Image.convert(mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256)`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert)] * A bilevel image (mode “1”) is treated as a greyscale (“L”) image by this method. [[`Image.histogram(mask=None, extrema=None)`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.histogram),[`Image.entropy(mask=None, extrema=None)`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.entropy)] * Parameters: threshold – All pixels above this greyscale level are inverted. [[`PIL.ImageOps.solarize(image, threshold=128)`](https://pillow.readthedocs.io/en/stable/reference/ImageOps.html#PIL.ImageOps.solarize)]
2023-10-19T08:19:08Z
10.1
python-pillow/Pillow
7,383
python-pillow__Pillow-7383
[ "7381" ]
52c6d686135e13df23f05cfe34d393b9d6e981f6
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -588,6 +588,7 @@ def exif_transpose(image, *, in_place=False): with the transposition applied. If there is no transposition, a copy of the image will be returned. """ + image.load() image_exif = image.getexif() orientation = image_exif.get(ExifTags.Base.Orientation) method = { diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -1203,20 +1203,6 @@ def load(self): return super().load() def load_end(self): - if self._tile_orientation: - method = { - 2: Image.Transpose.FLIP_LEFT_RIGHT, - 3: Image.Transpose.ROTATE_180, - 4: Image.Transpose.FLIP_TOP_BOTTOM, - 5: Image.Transpose.TRANSPOSE, - 6: Image.Transpose.ROTATE_270, - 7: Image.Transpose.TRANSVERSE, - 8: Image.Transpose.ROTATE_90, - }.get(self._tile_orientation) - if method is not None: - self.im = self.im.transpose(method) - self._size = self.im.size - # allow closing if we're on the first frame, there's no next # This is the ImageFile.load path only, libtiff specific below. if not self.is_animated: @@ -1233,6 +1219,10 @@ def load_end(self): continue exif.get_ifd(key) + ImageOps.exif_transpose(self, in_place=True) + if ExifTags.Base.Orientation in self.tag_v2: + del self.tag_v2[ExifTags.Base.Orientation] + def _load_libtiff(self): """Overload method triggered when we detect a compressed tiff Calls out to libtiff""" @@ -1542,8 +1532,6 @@ def _setup(self): palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]] self.palette = ImagePalette.raw("RGB;L", b"".join(palette)) - self._tile_orientation = self.tag_v2.get(ExifTags.Base.Orientation) - # # --------------------------------------------------------------------
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -8,7 +8,7 @@ import pytest -from PIL import Image, ImageFilter, TiffImagePlugin, TiffTags, features +from PIL import Image, ImageFilter, ImageOps, TiffImagePlugin, TiffTags, features from PIL.TiffImagePlugin import SAMPLEFORMAT, STRIPOFFSETS, SUBIFD from .helper import ( @@ -1035,7 +1035,18 @@ def test_orientation(self): with Image.open("Tests/images/g4_orientation_1.tif") as base_im: for i in range(2, 9): with Image.open("Tests/images/g4_orientation_" + str(i) + ".tif") as im: + assert 274 in im.tag_v2 + im.load() + assert 274 not in im.tag_v2 + + assert_image_similar(base_im, im, 0.7) + + def test_exif_transpose(self): + with Image.open("Tests/images/g4_orientation_1.tif") as base_im: + for i in range(2, 9): + with Image.open("Tests/images/g4_orientation_" + str(i) + ".tif") as im: + im = ImageOps.exif_transpose(im) assert_image_similar(base_im, im, 0.7)
ImageOps.exif_transpose not expected behaviour for TIFF images ### What did you do? I have a simple tiff image 150x100px rotated 90 degrees according to exif tag: [sample-out.zip](https://github.com/python-pillow/Pillow/files/12549680/sample-out.zip) ```bash exiftool -n sample-out.tif ... Image Width : 150 Image Height : 100 Orientation : 6 ... ``` I tried to rotate the image in Pillow according to EXIF Orientation tag. ### What did you expect to happen? New resolution is 100x150, correct orientation ### What actually happened? New resolution is 150x100, image transposed wrong way ### What are your OS, Python and Pillow versions? * OS: Ubuntu * Python: 3.10 * Pillow: 9.3.0 ```python from PIL import Image, ImageOps im = Image.open('sample-out.tif') print(im.size) # (150, 100) - correct im = ImageOps.exif_transpose(im) print(im.size) # (150, 100) - not correct im.save('output.tif') # you may save and see that now image rotated 540 degrees and does not contain ``` ```bash exiftool -n output.tif ... Image Width : 150 Image Height : 100 # there is not Orientation tag anymore ... ``` ### Reason ``Image.transpose`` calls ``Image.load()``. ``Image.load()``calls ``TiffImageFile.load()`` ``TiffImageFile.load()`` calls ``ImageFile.load()`` ``ImageFile.load()`` calls ``TiffImageFile.load_end()`` ``load_end()`` transposes image. After ``Image.load()`` is done, image is transposed again.
I've created PR #7383 to resolve this.
2023-09-07T22:49:54Z
10
python-pillow/Pillow
7,420
python-pillow__Pillow-7420
[ "7384" ]
b723e9e62e4706a85f7e44cb42b3d838dae5e546
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -915,7 +915,7 @@ def convert( self.load() - has_transparency = self.info.get("transparency") is not None + has_transparency = "transparency" in self.info if not mode and self.mode == "P": # determine default mode if self.palette: @@ -1531,6 +1531,24 @@ def getpalette(self, rawmode="RGB"): rawmode = mode return list(self.im.getpalette(mode, rawmode)) + @property + def has_transparency_data(self) -> bool: + """ + Determine if an image has transparency data, whether in the form of an + alpha channel, a palette with an alpha channel, or a "transparency" key + in the info dictionary. + + Note the image might still appear solid, if all of the values shown + within are opaque. + + :returns: A boolean. + """ + return ( + self.mode in ("LA", "La", "PA", "RGBA", "RGBa") + or (self.mode == "P" and self.palette.mode.endswith("A")) + or "transparency" in self.info + ) + def apply_transparency(self): """ If a P mode image has a "transparency" key in the info dictionary, diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py --- a/src/PIL/WebPImagePlugin.py +++ b/src/PIL/WebPImagePlugin.py @@ -332,12 +332,7 @@ def _save(im, fp, filename): exact = 1 if im.encoderinfo.get("exact") else 0 if im.mode not in _VALID_WEBP_LEGACY_MODES: - alpha = ( - "A" in im.mode - or "a" in im.mode - or (im.mode == "P" and "transparency" in im.info) - ) - im = im.convert("RGBA" if alpha else "RGB") + im = im.convert("RGBA" if im.has_transparency_data else "RGB") data = _webp.WebPEncode( im.tobytes(),
diff --git a/Tests/test_file_webp.py b/Tests/test_file_webp.py --- a/Tests/test_file_webp.py +++ b/Tests/test_file_webp.py @@ -234,3 +234,13 @@ def test_duration(self, tmp_path): with Image.open(out_webp) as reloaded: assert reloaded.info["duration"] == 1000 + + def test_roundtrip_rgba_palette(self, tmp_path): + temp_file = str(tmp_path / "temp.webp") + im = Image.new("RGBA", (1, 1)).convert("P") + assert im.mode == "P" + assert im.palette.mode == "RGBA" + im.save(temp_file) + + with Image.open(temp_file) as im: + assert im.getpixel((0, 0)) == (0, 0, 0, 0) diff --git a/Tests/test_image.py b/Tests/test_image.py --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -906,6 +906,31 @@ def test_zero_tobytes(self, size): im = Image.new("RGB", size) assert im.tobytes() == b"" + def test_has_transparency_data(self): + for mode in ("1", "L", "P", "RGB"): + im = Image.new(mode, (1, 1)) + assert not im.has_transparency_data + + for mode in ("LA", "La", "PA", "RGBA", "RGBa"): + im = Image.new(mode, (1, 1)) + assert im.has_transparency_data + + # P mode with "transparency" info + with Image.open("Tests/images/first_frame_transparency.gif") as im: + assert "transparency" in im.info + assert im.has_transparency_data + + # RGB mode with "transparency" info + with Image.open("Tests/images/rgb_trns.png") as im: + assert "transparency" in im.info + assert im.has_transparency_data + + # P mode with RGBA palette + im = Image.new("RGBA", (1, 1)).convert("P") + assert im.mode == "P" + assert im.palette.mode == "RGBA" + assert im.has_transparency_data + def test_apply_transparency(self): im = Image.new("P", (1, 1)) im.putpalette((0, 0, 0, 1, 1, 1))
Method to test if image has transparency/alpha [**2023/09/11 edit**] adding a tl;dr: 1. Online sources do not agree on a single method to check for either transparency (actual transparent pixels) or the presence of an alpha channel (whether or not it is opaque), and for all the examples I've found, it's easy to craft examples on which they fail. It would be useful to have an authoritative correct solution from someone who really understands Pillow/images that handles all the edge cases. Or in lieu of that, we could crowd-source one here. 2. Given the frequency of the question and the widespread incorrect code, it seems like it'd be useful to add this feature to Pillow itself. Original post: I found myself wanting to check if an image had an alpha channel/transparency (I'm allowing for a distinction between those, perhaps there isn't a meaningful one). I was trying to convert some optimised images that didn't contain any transparency, so wanted to do something different in that case. Checking for this is slightly tricky though, and I've seen incorrect logic posted elsewhere, e.g. [this stackoverflow post](https://stackoverflow.com/a/35859141/5506429) references [_this_ stackoverflow post](http://stackoverflow.com/a/1963146) which states to use: ```python img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info) ``` But palette-mode images can store their transparency in at least two ways, in `img.info`, or the palette itself might be `RGBA`. If you run the following ```python img = Image.new("RGBA", (100, 100), (128, 128, 128, 128)).quantize() print(img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info)) # False ``` the result is `False`, but clearly it has alpha values in the palette: ```python print(img.palette.mode) # 'RGBA' print(img.palette.colors) # {(128, 128, 128, 128): 0, (0, 0, 0, 0): 1} ``` Would it be possible to add something like `img.has_alpha()` or `img.has_transparency()` to help here? I'm not familiar enough with Pillow's image formats to say whether checking the mode of the palette in addition to the checks above would be exhaustive. Perhaps someone can clarify? Is it sufficient to check `img.palette.mode == 'RGBA'`? `.quantize()` does not seem to like an `LA` image, but if I manually set the palette mode and colors, it works with `show()`. Then there are other esoteric modes with alpha channels. So perhaps something like this will work? ```python alpha_modes = {"RGBA", "RGBa", "LA", "La", "PA"} return img.mode in alpha_modes or ( img.mode == "P" and ("transparency" in img.info or img.palette.mode in alpha_modes) ) ``` but I very easily could have missed something due to inexperience with the unusual image formats. (Happy to have a go at the implementation if that would be of assistance!)
A side comment that I'm not sure how to phrase - you mention two StackOverflow posts, a 2016 StackOverflow post referencing a StackOverflow post from 2009. If the problem is that old, I have to imagine the awkward solutions are also well-ingrained in the behaviour of users by now, and that whatever happens here, posts from 2009 (which is actually before Pillow even existed) will still be there, offering a different way of doing things. This is just part of dealing with a library that has been around for a long time. Given that you can have RGBA images that are fully solid, the method you're describing is sort of not describing whether an image **has** transparency, but whether it **might** have transparency. I presume you're not interested in a method that checks each pixel to see if it has transparency or not, because you correctly think that would be slower? Thanks for the comment! Yeah I agree about the legacy here. But it's a bit of "the best time to act was in 2009, the second best time to act is now" sort of situation IMO. My point was that those well-ingrained solutions are actually _incorrect_, hence the huge benefit in a library-approved correct method (as opposed to just leaving people to use a commonly accepted workaround, which would be more okay if it was correct). I found those Stack Overflow posts through searching for sensible terms, and it's not uncommon to see a post on SO get a new solution many years later when a library gets updated, and that solution slowly gets upvoted. Regarding solid RGBA images – that's why I left the door open for a semantic difference between "has alpha" and "has transparency". When it comes to my own use case, I was interested in not _just_ removing transparency but removing the alpha channel (even if it was opaque). Though I can see utility in both features, and while checking for transparency would be slower, I'm not sure if it would be too slow to be useful. I figured it was something that could come out in a discussion, anyway. For clarity on terms: we're agreed that alpha does not imply transparency, does transparency imply alpha? Are there any ways to achieve transparency in Pillow that do not use an alpha channel? Genuine question as to whether this is a subset or a Venn diagram...! A colleague just sent me this post, which seems like a nicely well-researched `has_transparency` method (unlike the one in my post which was not well-researched, and just supposed to be `has_alpha`) [https://stackoverflow.com/a/58567453/5506429](https://stackoverflow.com/a/58567453/5506429) though an answer by another author seems to check for different cases again [https://stackoverflow.com/a/76268100/5506429](https://stackoverflow.com/a/76268100/5506429) Though both of those answers rely on `transparency` being a key in `img.info`, which is not the case when you quantize an `RGBA` image ```python img = Image.new("RGBA", (100, 100), (128, 128, 128, 128)).quantize() print(img.info) # {} ``` perhaps that's actually a bug in `.quantize()` or `.new()` but seems all of these have some issues. > Though both of those answers rely on `transparency` being a key in `img.info`, which is not the case when you quantize an `RGBA` image > > ```python > img = Image.new("RGBA", (100, 100), (128, 128, 128, 128)).quantize() > print(img.info) # {} > ``` > > perhaps that's actually a bug in `.quantize()` or `.new()` but seems all of these have some issues. If the behaviour of `quantize()` is not to keep any transparency, then we probably don't want to change that default behaviour and defy existing user's expectations. Perhaps another argument could be added to enable transparency to stay around, but this seems to be getting away from your original request. > Regarding solid RGBA images – that's why I left the door open for a semantic difference between "has alpha" and "has transparency". Speaking for myself, I wouldn't have naturally understood a difference between those two method names. > Are there any ways to achieve transparency in Pillow that do not use an alpha channel? I think you've already posted an example of this, that P mode images can have a transparency index? > When it comes to my own use case, I was interested in not just removing transparency but removing the alpha channel (even if it was opaque) So this is the same as https://stackoverflow.com/questions/35859140/remove-transparency-alpha-from-any-image-using-pil/35859141#35859141. Would it be simpler to cut out the middleman of checking for transparency, and just have a method that removes transparency? > If the behaviour of `quantize()` is not to keep any transparency, then we probably don't want to change that default behaviour and defy existing user's expectations. Sorry, `quantize()` _does_ retain transparency. That code sample I posted puts the alpha values into the palette. If you save it as a png and reload it, then it comes back in `.info['transparency']`. > > Are there any ways to achieve transparency in Pillow that do not use an alpha channel? > > I think you've already posted an example of this, that P mode images can have a transparency index? Good point :) > So this is the same as https://stackoverflow.com/questions/35859140/remove-transparency-alpha-from-any-image-using-pil/35859141#35859141. Would it be simpler to cut out the middleman of checking for transparency, and just have a method that removes transparency? It does seem that removing transparency is the most common request here and I'd definitely make use of such a method, but I think it'd be complicated. I specifically wanted to do something like: ```python if has_alpha: composite with a specific colour background remove_alpha ``` but in that case, after `alpha_composite` all the alpha values are `255` so for `remove_alpha` I was happy to do `.convert("RGB")`. For a more fully-fledged `remove_transparency` method, it'd presumably need to have an option to add a background, and also retain the original mode? I do also have a use case where I just want to check for particular images that _actually_ have transparent pixels – not to remove the transparency, but to determine an output format (since jpg doesn't support it for example). The examples from SO handle every file I've seen so far, I just can't help but notice I can construct an image where they'd fail.
2023-09-25T10:36:10Z
10
python-pillow/Pillow
7,412
python-pillow__Pillow-7412
[ "7411" ]
4ecf1df4ea63457040f63adaeea35996913b6ac1
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -242,7 +242,7 @@ def contain(image, size, method=Image.Resampling.BICUBIC): Returns a resized version of the image, set to the maximum width and height within the requested size, while maintaining the original aspect ratio. - :param image: The image to resize and crop. + :param image: The image to resize. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: Resampling method to use. Default is @@ -266,6 +266,35 @@ def contain(image, size, method=Image.Resampling.BICUBIC): return image.resize(size, resample=method) +def cover(image, size, method=Image.Resampling.BICUBIC): + """ + Returns a resized version of the image, so that the requested size is + covered, while maintaining the original aspect ratio. + + :param image: The image to resize. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :return: An image. + """ + + im_ratio = image.width / image.height + dest_ratio = size[0] / size[1] + + if im_ratio != dest_ratio: + if im_ratio < dest_ratio: + new_height = round(image.height / image.width * size[0]) + if new_height != size[1]: + size = (size[0], new_height) + else: + new_width = round(image.width / image.height * size[1]) + if new_width != size[0]: + size = (new_width, size[1]) + return image.resize(size, resample=method) + + def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5)): """ Returns a resized and padded version of the image, expanded to fill the
diff --git a/Tests/test_imageops.py b/Tests/test_imageops.py --- a/Tests/test_imageops.py +++ b/Tests/test_imageops.py @@ -39,6 +39,9 @@ def test_sanity(): ImageOps.contain(hopper("L"), (128, 128)) ImageOps.contain(hopper("RGB"), (128, 128)) + ImageOps.cover(hopper("L"), (128, 128)) + ImageOps.cover(hopper("RGB"), (128, 128)) + ImageOps.crop(hopper("L"), 1) ImageOps.crop(hopper("RGB"), 1) @@ -119,6 +122,20 @@ def test_contain_round(): assert new_im.height == 5 +@pytest.mark.parametrize( + "image_name, expected_size", + ( + ("colr_bungee.png", (1024, 256)), # landscape + ("imagedraw_stroke_multiline.png", (256, 640)), # portrait + ("hopper.png", (256, 256)), # square + ), +) +def test_cover(image_name, expected_size): + with Image.open("Tests/images/" + image_name) as im: + new_im = ImageOps.cover(im, (256, 256)) + assert new_im.size == expected_size + + def test_pad(): # Same ratio im = hopper()
Function to downscale to minimum size <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What do you want to do? I want to downscale/resize an image to a minimum size without changing its aspect ratio. This could be useful for shrinking large profile pictures, or shrinking an image to save processing time during future operations on an image. ### How would you expect it to be implemented? I'd like to call a function on an `Image` object, like `downscale_to_min(img, min_width, min_height)`. Example: ```python img = Image.open("filepath/to/my/picture.png") print(img.size) # (1400, 100) img.downscale_to_min(500, 500) print(img.size) # (700, 500) ``` ### Any context? There a similar function to this, `thumbnail()`, where you set the _maximum_ size to scale an image to. It's like drawing a box around an image, and making sure no side of the image grows over the borders. I tried to visualize it here, red are the borders (the maximum size passed to `thumbnail()`, and green is the image: <details><summary>Click to expand</summary> ![Thumbnail](https://github.com/python-pillow/Pillow/assets/119804311/289bd185-8ae7-4189-bf76-321b2f3f7630) </details> This function would be similar, except the box is now on the inside of the image, and the no side can shrink _under_ the borders Again, visualized: <details><summary>Click to expand</summary> ![Down to min](https://github.com/python-pillow/Pillow/assets/119804311/f544d4fb-c55b-4ae7-bc11-a438adeb2633) </details> ### What are your OS, Python and Pillow versions? * OS: Fedora Linux 38 * Python: 3.11 * Pillow: 10.0.1 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> This is a basic function that implements the functionality using existing PIL functions. ```python def downscale_to_min(img, min_width, min_height): desired_ratio = min_height / min_width img_ratio = img.height / img.width if img_ratio > desired_ratio: desired_height = min_height downscale_factor = min_height / img.height desired_width = img.width * downscale_factor else: desired_width = min_width downscale_factor = min_width / img.width desired_height = img.height * downscale_factor img.resize((desired_width, desired_height)) ```
I think that `ImageOps` is a better home for this than `Image`, since we have similar methods there already. I've created PR #7412 to add the new function.
2023-09-21T01:48:54Z
10
python-pillow/Pillow
7,302
python-pillow__Pillow-7302
[ "7301" ]
3c5324b07c2ed98bc0ec94bd5c6a30f9c66e42fb
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -1042,6 +1042,7 @@ def getxmp(self): "LA": ("LA", b"\x08\x04"), "I": ("I;16B", b"\x10\x00"), "I;16": ("I;16B", b"\x10\x00"), + "I;16B": ("I;16B", b"\x10\x00"), "P;1": ("P;1", b"\x01\x03"), "P;2": ("P;2", b"\x02\x03"), "P;4": ("P;4", b"\x04\x03"),
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -92,11 +92,11 @@ def test_sanity(self, tmp_path): assert im.format == "PNG" assert im.get_format_mimetype() == "image/png" - for mode in ["1", "L", "P", "RGB", "I", "I;16"]: + for mode in ["1", "L", "P", "RGB", "I", "I;16", "I;16B"]: im = hopper(mode) im.save(test_file) with Image.open(test_file) as reloaded: - if mode == "I;16": + if mode in ("I;16", "I;16B"): reloaded = reloaded.convert(mode) assert_image_equal(reloaded, im)
Enable writing I;16B images as PNG While investigating an ImageIO issue concerning behavior on big-endian architectures I've noticed that pillow's PNG plugin currently doesn't allow writing 16-bit big-endian images to PNG. `I;16` is already supported, so I was wondering if it would be possible to add `I;16B` as well. From what I can see, the only change needed to support this would be to add the line `"I;16B": ("I;16B", b"\x10\x00"),` to this dict: https://github.com/python-pillow/Pillow/blob/3c5324b07c2ed98bc0ec94bd5c6a30f9c66e42fb/src/PIL/PngImagePlugin.py#L1035-L1051 With this change we would be able to do 16 bit round-trips on big-endian, i.e., we can decode the pixel data directly into a 16 bit big-endian buffer and then use that same buffer when encoding as PNG. This would improve performance and streamline working with native encoding on big-endian machines.
2023-07-24T07:22:13Z
10
python-pillow/Pillow
7,274
python-pillow__Pillow-7274
[ "7324" ]
7b17f9bbb4ac7e79c855efcc2d57dd89e8d8ced8
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1385,7 +1385,7 @@ def getextrema(self): def _getxmp(self, xmp_tags): def get_name(tag): - return tag.split("}")[1] + return re.sub("^{[^}]+}", "", tag) def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py --- a/src/PIL/JpegImagePlugin.py +++ b/src/PIL/JpegImagePlugin.py @@ -496,7 +496,7 @@ def getxmp(self): for segment, content in self.applist: if segment == "APP1": - marker, xmp_tags = content.rsplit(b"\x00", 1) + marker, xmp_tags = content.split(b"\x00")[:2] if marker == b"http://ns.adobe.com/xap/1.0/": return self._getxmp(xmp_tags) return {}
diff --git a/Tests/images/xmp_no_prefix.jpg b/Tests/images/xmp_no_prefix.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/xmp_no_prefix.jpg differ diff --git a/Tests/images/xmp_padded.jpg b/Tests/images/xmp_padded.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/xmp_padded.jpg differ diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -882,7 +882,10 @@ def read(n=-1): def test_getxmp(self): with Image.open("Tests/images/xmp_test.jpg") as im: if ElementTree is None: - with pytest.warns(UserWarning): + with pytest.warns( + UserWarning, + match="XMP data cannot be read without defusedxml dependency", + ): assert im.getxmp() == {} else: xmp = im.getxmp() @@ -905,6 +908,28 @@ def test_getxmp(self): with Image.open("Tests/images/hopper.jpg") as im: assert im.getxmp() == {} + def test_getxmp_no_prefix(self): + with Image.open("Tests/images/xmp_no_prefix.jpg") as im: + if ElementTree is None: + with pytest.warns( + UserWarning, + match="XMP data cannot be read without defusedxml dependency", + ): + assert im.getxmp() == {} + else: + assert im.getxmp() == {"xmpmeta": {"key": "value"}} + + def test_getxmp_padded(self): + with Image.open("Tests/images/xmp_padded.jpg") as im: + if ElementTree is None: + with pytest.warns( + UserWarning, + match="XMP data cannot be read without defusedxml dependency", + ): + assert im.getxmp() == {} + else: + assert im.getxmp() == {"xmpmeta": None} + @pytest.mark.timeout(timeout=1) def test_eof(self): # Even though this decoder never says that it is finished diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -665,7 +665,10 @@ def test_plte_length(self, tmp_path): def test_getxmp(self): with Image.open("Tests/images/color_snakes.png") as im: if ElementTree is None: - with pytest.warns(UserWarning): + with pytest.warns( + UserWarning, + match="XMP data cannot be read without defusedxml dependency", + ): assert im.getxmp() == {} else: xmp = im.getxmp() diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -734,7 +734,10 @@ def test_discard_icc_profile(self, tmp_path): def test_getxmp(self): with Image.open("Tests/images/lab.tif") as im: if ElementTree is None: - with pytest.warns(UserWarning): + with pytest.warns( + UserWarning, + match="XMP data cannot be read without defusedxml dependency", + ): assert im.getxmp() == {} else: xmp = im.getxmp() diff --git a/Tests/test_file_webp_metadata.py b/Tests/test_file_webp_metadata.py --- a/Tests/test_file_webp_metadata.py +++ b/Tests/test_file_webp_metadata.py @@ -118,7 +118,10 @@ def test_getxmp(): with Image.open("Tests/images/flower2.webp") as im: if ElementTree is None: - with pytest.warns(UserWarning): + with pytest.warns( + UserWarning, + match="XMP data cannot be read without defusedxml dependency", + ): assert im.getxmp() == {} else: assert (
Inconsistent XMP data retrieval: Failure with specific JPEG files ### What did you do? I'm loading a .jpg image using Pillow in an attempt to extract the XMP metadata: ```python from PIL import Image image = Image.open("lib/filename_example_1.jpg") raw_xmp_info = image.getxmp() ``` ### What did you expect to happen? I'm expecting `getxmp()` to return a dictionary containing the image's XMP metadata: `{'xmpmeta: {<metadata>}`. ### What actually happened? Pillow can't extract the XMP metadata from the image: ```pytb Traceback (most recent call last): File "/path/to/main.py", line 4, in <module> raw_xmp_info = image.getxmp() ^^^^^^^^^^^^^^ File "/path/to/venv/site-packages/PIL/JpegImagePlugin.py", line 501, in getxmp return self._getxmp(xmp_tags) ^^^^^^^^^^^^^^^^^^^^^^ File "/path/to/venv/site-packages/PIL/Image.py", line 1410, in _getxmp return {get_name(root.tag): get_value(root)} ^^^^^^^^^^^^^^^ File "/path/to/venv/site-packages/PIL/Image.py", line 1391, in get_value child_value = get_value(child) ^^^^^^^^^^^^^^^^ File "/path/to/venv/site-packages/PIL/Image.py", line 1391, in get_value child_value = get_value(child) ^^^^^^^^^^^^^^^^ File "/path/to/venv/site-packages/PIL/Image.py", line 1386, in get_value value = {get_name(k): v for k, v in element.attrib.items()} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/path/to/venv/site-packages/PIL/Image.py", line 1386, in <dictcomp> value = {get_name(k): v for k, v in element.attrib.items()} ^^^^^^^^^^^ File "/path/to/venv/site-packages/PIL/Image.py", line 1383, in get_name return tag.split("}")[1] ~~~~~~~~~~~~~~^^^ IndexError: list index out of range ``` ### What are your OS, Python and Pillow versions? * OS: WSL2 - Ubuntu 22.04.2 LTS * Python: 3.11.4 * Pillow: 10.0.0 (also getting the error with 9.x) ### Additional information. Printing `image.info` reveals: ```python {'jfif': 257, 'jfif_version': (1, 1), 'dpi': (240, 240), 'jfif_unit': 1, 'jfif_density': (240, 240), 'photoshop': {1028: b'\x1c\x02\x00\x00\x02\x00\x02\x1c\x01Z\x00\x03\x1b%G\x1c\x02i\x00\x1f"Enkeltrick"-Betrug vor Gericht\x1c\x02\x19\x00\x14.Nordrhein-Westfalen\x1c\x02\x19\x00\x03Ges\x1c\x02\x19\x00\rKriminalit\xc3\xa4t\x1c\x02\x19\x00\x03lnw\x1c\x02\x19\x00\x08Prozesse\x1c\x02\x19\x00\tRegierung\x1c\x02\x19\x00\x08Senioren\x1c\x02\x19\x00\nSicherheit\x1c\x02\x19\x00\x07Telefon\x1c\x02\x19\x00\x0bVermischtes\x1c\x02\x19\x00\x0c\xc3\x9cberwachung\x1c\x02\x19\x00\x12\xc3\x9cberwachungsstaat\x1c\x02\x19\x00\x07XGV2011\x1c\x02Z\x00\x07Dresden\x1c\x02_\x00\x07Sachsen\x1c\x02e\x00\x0bDeutschland\x1c\x02d\x00\x03DEU\x1c\x027\x00\x0820131216\x1c\x02P\x00\nArno Burgi\x1c\x02t\x00-picture alliance / Arno Burgi/dpa-Zentralbild\x1c\x02z\x00\x17abu vfd htf kno sup bsc\x1c\x02n\x00-picture alliance / Arno Burgi/dpa-Zentralbild\x1c\x02s\x00\x0fdpa-Zentralbild\x1c\x02\x05\x00\x0886540586\x1c\x02\x83\x00\tlandscape\x1c\x02x\x01uARCHIV\xc2\xa0- ILLUSTRATION - Eine Frau telefoniert am 16.12.2013 in Dresden (Sachsen) mit ihrem Mobiltelefon an der Wand zeichnet sich ihr Schatten ab. Beim Enkeltrick gaukeln Betr\xc3\xbcger ihren meist betagten Opfern am Telefon vor, ein naher Verwandter - etwa ein Enkel - zu sein. Foto: Arno Burgi/dpa (zu dpa vom 16.12.2016) Foto: Arno Burgi/dpa-Zentralbild +++ dpa-Bildfunk +++\x1c\x02(\x00\x00\x00'}, 'icc_profile': b'\x00\x00\x0cHLino\x02\x10\x00\x00mntrRGB XYZ \x07\xce\x00\x02\x00\t\x00\x06\x001\x00\x00acspMSFT\x00\x00\x00\x00IEC sRGB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf6\xd6\x00\x01\x00\x00\x00\x00\xd3-HP \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11cprt\x00\x00\x01P\x00\x00\x003desc\x00\x00\x01\x84\x00\x00\x00lwtpt\x00\x00\x01\xf0\x00\x00\x00\x14bkpt\x00\x00\x02\x04\x00\x00\x00\x14rXYZ\x00\x00\x02\x18\x00\x00\x00\x14gXYZ\x00\x00\x02,\x00\x00\x00\x14bXYZ\x00\x00\x02@\x00\x00\x00\x14dmnd\x00\x00\x02T\x00\x00\x00pdmdd\x00\x00\x02\xc4\x00\x00\x00\x88vued\x00\x00\x03L\x00\x00\x00\x86view\x00\x00\x03\xd4\x00\x00\x00$lumi\x00\x00\x03\xf8\x00\x00\x00\x14meas\x00\x00\x04\x0c\x00\x00\x00$tech\x00\x00\x040\x00\x00\x00\x0crTRC\x00\x00\x04<\x00\x00\x08\x0cgTRC\x00\x00\x04<\x00\x00\x08\x0cbTRC\x00\x00\x04<\x00\x00\x08\x0ctext\x00\x00\x00\x00Copyright (c) 1998 Hewlett-Packard Company\x00\x00desc\x00\x00\x00\x00\x00\x00\x00\x12sRGB IEC61966-2.1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x12sRGB IEC61966-2.1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00XYZ \x00\x00\x00\x00\x00\x00\xf3Q\x00\x01\x00\x00\x00\x01\x16\xccXYZ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00XYZ \x00\x00\x00\x00\x00\x00o\xa2\x00\x008\xf5\x00\x00\x03\x90XYZ \x00\x00\x00\x00\x00\x00b\x99\x00\x00\xb7\x85\x00\x00\x18\xdaXYZ \x00\x00\x00\x00\x00\x00$\xa0\x00\x00\x0f\x84\x00\x00\xb6\xcfdesc\x00\x00\x00\x00\x00\x00\x00\x16IEC http://www.iec.ch\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16IEC http://www.iec.ch\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00desc\x00\x00\x00\x00\x00\x00\x00.IEC 61966-2.1 Default RGB colour space - sRGB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.IEC 61966-2.1 Default RGB colour space - sRGB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00desc\x00\x00\x00\x00\x00\x00\x00,Reference Viewing Condition in IEC61966-2.1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00,Reference Viewing Condition in IEC61966-2.1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00view\x00\x00\x00\x00\x00\x13\xa4\xfe\x00\x14_.\x00\x10\xcf\x14\x00\x03\xed\xcc\x00\x04\x13\x0b\x00\x03\\\x9e\x00\x00\x00\x01XYZ \x00\x00\x00\x00\x00L\tV\x00P\x00\x00\x00W\x1f\xe7meas\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x8f\x00\x00\x00\x02sig \x00\x00\x00\x00CRT curv\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x05\x00\n\x00\x0f\x00\x14\x00\x19\x00\x1e\x00#\x00(\x00-\x002\x007\x00;\x00@\x00E\x00J\x00O\x00T\x00Y\x00^\x00c\x00h\x00m\x00r\x00w\x00|\x00\x81\x00\x86\x00\x8b\x00\x90\x00\x95\x00\x9a\x00\x9f\x00\xa4\x00\xa9\x00\xae\x00\xb2\x00\xb7\x00\xbc\x00\xc1\x00\xc6\x00\xcb\x00\xd0\x00\xd5\x00\xdb\x00\xe0\x00\xe5\x00\xeb\x00\xf0\x00\xf6\x00\xfb\x01\x01\x01\x07\x01\r\x01\x13\x01\x19\x01\x1f\x01%\x01+\x012\x018\x01>\x01E\x01L\x01R\x01Y\x01`\x01g\x01n\x01u\x01|\x01\x83\x01\x8b\x01\x92\x01\x9a\x01\xa1\x01\xa9\x01\xb1\x01\xb9\x01\xc1\x01\xc9\x01\xd1\x01\xd9\x01\xe1\x01\xe9\x01\xf2\x01\xfa\x02\x03\x02\x0c\x02\x14\x02\x1d\x02&\x02/\x028\x02A\x02K\x02T\x02]\x02g\x02q\x02z\x02\x84\x02\x8e\x02\x98\x02\xa2\x02\xac\x02\xb6\x02\xc1\x02\xcb\x02\xd5\x02\xe0\x02\xeb\x02\xf5\x03\x00\x03\x0b\x03\x16\x03!\x03-\x038\x03C\x03O\x03Z\x03f\x03r\x03~\x03\x8a\x03\x96\x03\xa2\x03\xae\x03\xba\x03\xc7\x03\xd3\x03\xe0\x03\xec\x03\xf9\x04\x06\x04\x13\x04 \x04-\x04;\x04H\x04U\x04c\x04q\x04~\x04\x8c\x04\x9a\x04\xa8\x04\xb6\x04\xc4\x04\xd3\x04\xe1\x04\xf0\x04\xfe\x05\r\x05\x1c\x05+\x05:\x05I\x05X\x05g\x05w\x05\x86\x05\x96\x05\xa6\x05\xb5\x05\xc5\x05\xd5\x05\xe5\x05\xf6\x06\x06\x06\x16\x06\'\x067\x06H\x06Y\x06j\x06{\x06\x8c\x06\x9d\x06\xaf\x06\xc0\x06\xd1\x06\xe3\x06\xf5\x07\x07\x07\x19\x07+\x07=\x07O\x07a\x07t\x07\x86\x07\x99\x07\xac\x07\xbf\x07\xd2\x07\xe5\x07\xf8\x08\x0b\x08\x1f\x082\x08F\x08Z\x08n\x08\x82\x08\x96\x08\xaa\x08\xbe\x08\xd2\x08\xe7\x08\xfb\t\x10\t%\t:\tO\td\ty\t\x8f\t\xa4\t\xba\t\xcf\t\xe5\t\xfb\n\x11\n\'\n=\nT\nj\n\x81\n\x98\n\xae\n\xc5\n\xdc\n\xf3\x0b\x0b\x0b"\x0b9\x0bQ\x0bi\x0b\x80\x0b\x98\x0b\xb0\x0b\xc8\x0b\xe1\x0b\xf9\x0c\x12\x0c*\x0cC\x0c\\\x0cu\x0c\x8e\x0c\xa7\x0c\xc0\x0c\xd9\x0c\xf3\r\r\r&\r@\rZ\rt\r\x8e\r\xa9\r\xc3\r\xde\r\xf8\x0e\x13\x0e.\x0eI\x0ed\x0e\x7f\x0e\x9b\x0e\xb6\x0e\xd2\x0e\xee\x0f\t\x0f%\x0fA\x0f^\x0fz\x0f\x96\x0f\xb3\x0f\xcf\x0f\xec\x10\t\x10&\x10C\x10a\x10~\x10\x9b\x10\xb9\x10\xd7\x10\xf5\x11\x13\x111\x11O\x11m\x11\x8c\x11\xaa\x11\xc9\x11\xe8\x12\x07\x12&\x12E\x12d\x12\x84\x12\xa3\x12\xc3\x12\xe3\x13\x03\x13#\x13C\x13c\x13\x83\x13\xa4\x13\xc5\x13\xe5\x14\x06\x14\'\x14I\x14j\x14\x8b\x14\xad\x14\xce\x14\xf0\x15\x12\x154\x15V\x15x\x15\x9b\x15\xbd\x15\xe0\x16\x03\x16&\x16I\x16l\x16\x8f\x16\xb2\x16\xd6\x16\xfa\x17\x1d\x17A\x17e\x17\x89\x17\xae\x17\xd2\x17\xf7\x18\x1b\x18@\x18e\x18\x8a\x18\xaf\x18\xd5\x18\xfa\x19 \x19E\x19k\x19\x91\x19\xb7\x19\xdd\x1a\x04\x1a*\x1aQ\x1aw\x1a\x9e\x1a\xc5\x1a\xec\x1b\x14\x1b;\x1bc\x1b\x8a\x1b\xb2\x1b\xda\x1c\x02\x1c*\x1cR\x1c{\x1c\xa3\x1c\xcc\x1c\xf5\x1d\x1e\x1dG\x1dp\x1d\x99\x1d\xc3\x1d\xec\x1e\x16\x1e@\x1ej\x1e\x94\x1e\xbe\x1e\xe9\x1f\x13\x1f>\x1fi\x1f\x94\x1f\xbf\x1f\xea \x15 A l \x98 \xc4 \xf0!\x1c!H!u!\xa1!\xce!\xfb"\'"U"\x82"\xaf"\xdd#\n#8#f#\x94#\xc2#\xf0$\x1f$M$|$\xab$\xda%\t%8%h%\x97%\xc7%\xf7&\'&W&\x87&\xb7&\xe8\'\x18\'I\'z\'\xab\'\xdc(\r(?(q(\xa2(\xd4)\x06)8)k)\x9d)\xd0*\x02*5*h*\x9b*\xcf+\x02+6+i+\x9d+\xd1,\x05,9,n,\xa2,\xd7-\x0c-A-v-\xab-\xe1.\x16.L.\x82.\xb7.\xee/$/Z/\x91/\xc7/\xfe050l0\xa40\xdb1\x121J1\x821\xba1\xf22*2c2\x9b2\xd43\r3F3\x7f3\xb83\xf14+4e4\x9e4\xd85\x135M5\x875\xc25\xfd676r6\xae6\xe97$7`7\x9c7\xd78\x148P8\x8c8\xc89\x059B9\x7f9\xbc9\xf9:6:t:\xb2:\xef;-;k;\xaa;\xe8<\'<e<\xa4<\xe3="=a=\xa1=\xe0> >`>\xa0>\xe0?!?a?\xa2?\xe2@#@d@\xa6@\xe7A)AjA\xacA\xeeB0BrB\xb5B\xf7C:C}C\xc0D\x03DGD\x8aD\xceE\x12EUE\x9aE\xdeF"FgF\xabF\xf0G5G{G\xc0H\x05HKH\x91H\xd7I\x1dIcI\xa9I\xf0J7J}J\xc4K\x0cKSK\x9aK\xe2L*LrL\xbaM\x02MJM\x93M\xdcN%NnN\xb7O\x00OIO\x93O\xddP\'PqP\xbbQ\x06QPQ\x9bQ\xe6R1R|R\xc7S\x13S_S\xaaS\xf6TBT\x8fT\xdbU(UuU\xc2V\x0fV\\V\xa9V\xf7WDW\x92W\xe0X/X}X\xcbY\x1aYiY\xb8Z\x07ZVZ\xa6Z\xf5[E[\x95[\xe5\\5\\\x86\\\xd6]\']x]\xc9^\x1a^l^\xbd_\x0f_a_\xb3`\x05`W`\xaa`\xfcaOa\xa2a\xf5bIb\x9cb\xf0cCc\x97c\xebd@d\x94d\xe9e=e\x92e\xe7f=f\x92f\xe8g=g\x93g\xe9h?h\x96h\xeciCi\x9ai\xf1jHj\x9fj\xf7kOk\xa7k\xfflWl\xafm\x08m`m\xb9n\x12nkn\xc4o\x1eoxo\xd1p+p\x86p\xe0q:q\x95q\xf0rKr\xa6s\x01s]s\xb8t\x14tpt\xccu(u\x85u\xe1v>v\x9bv\xf8wVw\xb3x\x11xnx\xccy*y\x89y\xe7zFz\xa5{\x04{c{\xc2|!|\x81|\xe1}A}\xa1~\x01~b~\xc2\x7f#\x7f\x84\x7f\xe5\x80G\x80\xa8\x81\n\x81k\x81\xcd\x820\x82\x92\x82\xf4\x83W\x83\xba\x84\x1d\x84\x80\x84\xe3\x85G\x85\xab\x86\x0e\x86r\x86\xd7\x87;\x87\x9f\x88\x04\x88i\x88\xce\x893\x89\x99\x89\xfe\x8ad\x8a\xca\x8b0\x8b\x96\x8b\xfc\x8cc\x8c\xca\x8d1\x8d\x98\x8d\xff\x8ef\x8e\xce\x8f6\x8f\x9e\x90\x06\x90n\x90\xd6\x91?\x91\xa8\x92\x11\x92z\x92\xe3\x93M\x93\xb6\x94 \x94\x8a\x94\xf4\x95_\x95\xc9\x964\x96\x9f\x97\n\x97u\x97\xe0\x98L\x98\xb8\x99$\x99\x90\x99\xfc\x9ah\x9a\xd5\x9bB\x9b\xaf\x9c\x1c\x9c\x89\x9c\xf7\x9dd\x9d\xd2\x9e@\x9e\xae\x9f\x1d\x9f\x8b\x9f\xfa\xa0i\xa0\xd8\xa1G\xa1\xb6\xa2&\xa2\x96\xa3\x06\xa3v\xa3\xe6\xa4V\xa4\xc7\xa58\xa5\xa9\xa6\x1a\xa6\x8b\xa6\xfd\xa7n\xa7\xe0\xa8R\xa8\xc4\xa97\xa9\xa9\xaa\x1c\xaa\x8f\xab\x02\xabu\xab\xe9\xac\\\xac\xd0\xadD\xad\xb8\xae-\xae\xa1\xaf\x16\xaf\x8b\xb0\x00\xb0u\xb0\xea\xb1`\xb1\xd6\xb2K\xb2\xc2\xb38\xb3\xae\xb4%\xb4\x9c\xb5\x13\xb5\x8a\xb6\x01\xb6y\xb6\xf0\xb7h\xb7\xe0\xb8Y\xb8\xd1\xb9J\xb9\xc2\xba;\xba\xb5\xbb.\xbb\xa7\xbc!\xbc\x9b\xbd\x15\xbd\x8f\xbe\n\xbe\x84\xbe\xff\xbfz\xbf\xf5\xc0p\xc0\xec\xc1g\xc1\xe3\xc2_\xc2\xdb\xc3X\xc3\xd4\xc4Q\xc4\xce\xc5K\xc5\xc8\xc6F\xc6\xc3\xc7A\xc7\xbf\xc8=\xc8\xbc\xc9:\xc9\xb9\xca8\xca\xb7\xcb6\xcb\xb6\xcc5\xcc\xb5\xcd5\xcd\xb5\xce6\xce\xb6\xcf7\xcf\xb8\xd09\xd0\xba\xd1<\xd1\xbe\xd2?\xd2\xc1\xd3D\xd3\xc6\xd4I\xd4\xcb\xd5N\xd5\xd1\xd6U\xd6\xd8\xd7\\\xd7\xe0\xd8d\xd8\xe8\xd9l\xd9\xf1\xdav\xda\xfb\xdb\x80\xdc\x05\xdc\x8a\xdd\x10\xdd\x96\xde\x1c\xde\xa2\xdf)\xdf\xaf\xe06\xe0\xbd\xe1D\xe1\xcc\xe2S\xe2\xdb\xe3c\xe3\xeb\xe4s\xe4\xfc\xe5\x84\xe6\r\xe6\x96\xe7\x1f\xe7\xa9\xe82\xe8\xbc\xe9F\xe9\xd0\xea[\xea\xe5\xebp\xeb\xfb\xec\x86\xed\x11\xed\x9c\xee(\xee\xb4\xef@\xef\xcc\xf0X\xf0\xe5\xf1r\xf1\xff\xf2\x8c\xf3\x19\xf3\xa7\xf44\xf4\xc2\xf5P\xf5\xde\xf6m\xf6\xfb\xf7\x8a\xf8\x19\xf8\xa8\xf98\xf9\xc7\xfaW\xfa\xe7\xfbw\xfc\x07\xfc\x98\xfd)\xfd\xba\xfeK\xfe\xdc\xffm\xff\xff'} ``` Due to confidentiality reasons, I can not provide the image that I'm trying to process. However, I will provide the anonomised XMP metadata of the image that causes the error (`filename_example_1.jpg`) and one which doesn't cause an error (`filename_example_2.jpg`). This XMP metadata was extracted using https://www.imgonline.com.ua/. This shows that the metadata is present for both the working and the erroneous files. `filename_example_1.jpg` (erroneous): - About: Anonymous - City: Anonymous - State: Anonymous - Country: Anonymous - Credit: Anonymous - Source: Anonymous - Caption Writer: Anonymous - Headline: Anonymous - Create Date: Anonymous - Marked: True - Creator: Anonymous - Subject: Anonymous - Description: Anonymous - Rights: Anonymous - Title: 86540586 - Country Code: Anonymous - Creator Contact Info: Anonymous `filename_example_2.jpg` (successfully loaded by Pillow): - Metadata Date: Anonymous - Rating: 0 - Format: image/jpeg - Subject: Anonymous - Description: Anonymous - Creator: Anonymous - Rights: Anonymous - Lens: EF70-200mm f/4L USM - Image Number: 0 - Approximate Focus Distance: 4294967295 - Flash Compensation: 0 - Firmware: 1.3.3 - Color Mode: RGB - ICC Profile Name: sRGB IEC61966-2. 1 - City: Anonymous - State: Anonymous - Country: Anonymous - Category: SPO - Credit: Anonymous - Source: Anonymous - Headline: Anonymous - Date Created: Anonymous - Document ID: Anonymous - Instance ID: Anonymous - Original Document ID: Anonymous - History Action: saved, saved - History Instance ID: Anonymous - History When: Anonymous - History Sofware Agent: Anonymous - History Changed: /, / - Marked: True - Prefs: Tagged:0, ColorClass:0, Rating: 0, FrameNum:00115 - PM Version: PM4 - Country Code: Anonymous - Location: Anonymous If anyone is able to provide some insights into this bug, please let me know!
2023-07-10T12:16:36Z
10
python-pillow/Pillow
7,151
python-pillow__Pillow-7151
[ "7149" ]
2a274a476088c610451370b9b78e7c63b7b31da3
diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -314,11 +314,11 @@ def rounded_rectangle( full_x, full_y = False, False if all(corners): - full_x = d >= x1 - x0 + full_x = d >= x1 - x0 - 1 if full_x: # The two left and two right corners are joined d = x1 - x0 - full_y = d >= y1 - y0 + full_y = d >= y1 - y0 - 1 if full_y: # The two top and two bottom corners are joined d = y1 - y0
diff --git a/Tests/images/imagedraw_rounded_rectangle_x_odd.png b/Tests/images/imagedraw_rounded_rectangle_x_odd.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_x_odd.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_y_odd.png b/Tests/images/imagedraw_rounded_rectangle_y_odd.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_y_odd.png differ diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -839,7 +839,9 @@ def test_rounded_rectangle_zero_radius(bbox): "xy, suffix", [ ((20, 10, 80, 90), "x"), + ((20, 10, 81, 90), "x_odd"), ((10, 20, 90, 80), "y"), + ((10, 20, 90, 81), "y_odd"), ((20, 20, 80, 80), "both"), ], )
rounded_rectangle raises an "y1 should be > y0" even when coordinates are correctly ordered ### What did you do? I recently updated one of my programs from 9.4 to 9.5 and got this new ValueError when drawing rounded rectangles on an image. After some trials and error, I think the bug only happens when the rectangle height equals `1 + 2*radius`. I'm not 200% confident about that, but that's all I got so far. The exact lines causing the error are https://github.com/python-pillow/Pillow/blob/2a274a476088c610451370b9b78e7c63b7b31da3/src/PIL/ImageDraw.py#L378-L383 ### What did you expect to happen? Well, PIL should be able to correctly calculate positions and draw my rounded corners. ### What actually happened? ``` Traceback (most recent call last): File "/.../test.py", line 17, in <module> main() File "/.../test.py", line 14, in main draw.rounded_rectangle(coordinates, radius=3, fill=(0, 0, 0)) File "/.../env/lib/python3.9/site-packages/PIL/ImageDraw.py", line 385, in rounded_rectangle self.draw.draw_rectangle(left, fill, 1) ValueError: y1 must be greater than or equal to y0 ``` ### What are your OS, Python and Pillow versions? * OS: macOS 13.3.1 * Python: 3.9.16 * Pillow: 9.5.0 ```python from PIL import Image, ImageDraw def main(): # get a 1021x340 image img = Image.new('RGB', (20, 20), color=(255, 255, 255)) # draw a rounded rectangle on it draw = ImageDraw.Draw(img) coordinates = ( (5, 0), (15, 7) ) # here's the bug: # on ImageDraw.py line 383, y1 from "left" will be 1px less than y0 draw.rounded_rectangle(coordinates, radius=3, fill=(0, 0, 0)) if __name__ == '__main__': main() ```
2023-05-10T03:43:29Z
9.5
python-pillow/Pillow
7,078
python-pillow__Pillow-7078
[ "7077" ]
b0c76535022b795f2c31d725131c54e8e10d1ff7
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -1892,6 +1892,10 @@ class AppendingTiffWriter: 8, # srational 4, # float 8, # double + 4, # ifd + 2, # unicode + 4, # complex + 8, # long8 ] # StripOffsets = 273
diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -96,10 +96,17 @@ def test_mac_tiff(self): assert_image_similar_tofile(im, "Tests/images/pil136.png", 1) - def test_bigtiff(self): + def test_bigtiff(self, tmp_path): with Image.open("Tests/images/hopper_bigtiff.tif") as im: assert_image_equal_tofile(im, "Tests/images/hopper.tif") + with Image.open("Tests/images/hopper_bigtiff.tif") as im: + # multistrip support not yet implemented + del im.tag_v2[273] + + outfile = str(tmp_path / "temp.tif") + im.save(outfile, save_all=True, append_images=[im], tiffinfo=im.tag_v2) + def test_set_legacy_api(self): ifd = TiffImagePlugin.ImageFileDirectory_v2() with pytest.raises(Exception) as e:
Saving TIFF stack does not support tags with type long8 Title pretty much says it all. I believe the problem is that this list doesn't contain long8: [here](https://github.com/python-pillow/Pillow/blob/4ffbbe194c5a1b8840f809574017ab5f1333695f/src/PIL/TiffImagePlugin.py#L1881) to reproduce ```python import numpy as np import PIL from PIL.TiffImagePlugin import ImageFileDirectory_v2 x = np.ones((2, 10, 10)) pilimgs = [PIL.Image.fromarray(i) for i in x] ifd = ImageFileDirectory_v2() ifd[256] = 10 ifd[257] = 10 ifd[65000] = 1234 ifd.tagtype[65000] = 16 pilimgs[0].save("testimgs.tif", save_all=True, tiffinfo=ifd, append_images=pilimgs[1:], format="tiff") ```
2023-04-09T23:23:36Z
9.5
python-pillow/Pillow
7,111
python-pillow__Pillow-7111
[ "811" ]
9636a2aaf1c31e46ab6faaef778ca7ed0db0870d
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -170,6 +170,8 @@ (MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"), (II, 1, (1,), 1, (8,), ()): ("L", "L"), (MM, 1, (1,), 1, (8,), ()): ("L", "L"), + (II, 1, (2,), 1, (8,), ()): ("L", "L"), + (MM, 1, (2,), 1, (8,), ()): ("L", "L"), (II, 1, (1,), 2, (8,), ()): ("L", "L;R"), (MM, 1, (1,), 2, (8,), ()): ("L", "L;R"), (II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),
diff --git a/Tests/images/8bit.s.tif b/Tests/images/8bit.s.tif new file mode 100644 Binary files /dev/null and b/Tests/images/8bit.s.tif differ diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -198,6 +198,12 @@ def test_save_unsupported_mode(self, tmp_path): with pytest.raises(OSError): im.save(outfile) + def test_8bit_s(self): + with Image.open("Tests/images/8bit.s.tif") as im: + im.load() + assert im.mode == "L" + assert im.getpixel((50, 50)) == 184 + def test_little_endian(self): with Image.open("Tests/images/16bit.cropped.tif") as im: assert im.getpixel((0, 0)) == 480
Fails to open OME-TIFF example data files [OME-TIFF](https://www.openmicroscopy.org/site/support/ome-model/ome-tiff/index.html) is a TIFF format that embeds some microscopy-specific metadata as an XML comment embedded in the TIFF header. Sample data is available at https://www.openmicroscopy.org/site/support/ome-model/ome-tiff/data.html, but PIL fails to open `single-channel.ome.tiff` (throwing `OSError: cannot identify image file 'single-channel.ome.tiff'`).
I'm not at a computer to test, but just to confirm: does this happen with Pillow (the PIL fork)? Which version of Pillow do you have? Yes, this is with Pillow 2.5.0, Python 3.4. I actually haven't tested this with PIL. The actual problem with that file is that it is specified as a bigendian 8-bit signed integer format, which we don't have listed in the formats that we support. This past includes a mode line that will read the format and store it in an unsigned integer. Visual inspection of the image looks okay. The XML from the OME format shows up in the tags directory. ```diff diff --git a/PIL/TiffImagePlugin.py b/PIL/TiffImagePlugin.py index 2e49931..d96542a 100644 --- a/PIL/TiffImagePlugin.py +++ b/PIL/TiffImagePlugin.py @@ -185,6 +185,7 @@ OPEN_INFO = { (MM, 1, 1, 1, (1,), ()): ("1", "1"), (MM, 1, 1, 2, (1,), ()): ("1", "1;R"), (MM, 1, 1, 1, (8,), ()): ("L", "L"), + (MM, 1, 2, 1, (8,), ()): ("L", "L"), #signed 8 bit??? (MM, 1, 1, 1, (8,8), (2,)): ("LA", "LA"), (MM, 1, 1, 2, (8,), ()): ("L", "L;R"), (MM, 1, 1, 1, (16,), ()): ("I;16B", "I;16B"), ``` The [Image file formats](http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html#tiff) doc does not mention this limitation. Is this a non-standard TIFF format? (I don't know.) There are many combinations, we support 60 or more of them. See lines ~145->212 of TiffImagePlugin for the combinations. I've never seen a signed 8bit image before, so if it's not rare, it's not exactly common either. We don't have a specific mode for signed 8 bit images, so while we can read the image, we don't actually report the bytes correctly. (we'd return 0-255, not -127->127). Just a direct link to the sample image - https://downloads.openmicroscopy.org/images/OME-TIFF/2016-06/bioformats-artificial/single-channel.ome.tiff I've created PR #7111 to resolve this.
2023-04-24T04:02:32Z
9.5
python-pillow/Pillow
6,954
python-pillow__Pillow-6954
[ "6953" ]
d48dca3dc46947867e5f28d42ed2eb93f5b2e6ae
diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -295,29 +295,37 @@ def rectangle(self, xy, fill=None, outline=None, width=1): if ink is not None and ink != fill and width != 0: self.draw.draw_rectangle(xy, ink, 0, width) - def rounded_rectangle(self, xy, radius=0, fill=None, outline=None, width=1): + def rounded_rectangle( + self, xy, radius=0, fill=None, outline=None, width=1, *, corners=None + ): """Draw a rounded rectangle.""" if isinstance(xy[0], (list, tuple)): (x0, y0), (x1, y1) = xy else: x0, y0, x1, y1 = xy + if corners is None: + corners = (True, True, True, True) d = radius * 2 - full_x = d >= x1 - x0 - if full_x: - # The two left and two right corners are joined - d = x1 - x0 - full_y = d >= y1 - y0 - if full_y: - # The two top and two bottom corners are joined - d = y1 - y0 - if full_x and full_y: - # If all corners are joined, that is a circle - return self.ellipse(xy, fill, outline, width) - - if d == 0: - # If the corners have no curve, that is a rectangle + full_x, full_y = False, False + if all(corners): + full_x = d >= x1 - x0 + if full_x: + # The two left and two right corners are joined + d = x1 - x0 + full_y = d >= y1 - y0 + if full_y: + # The two top and two bottom corners are joined + d = y1 - y0 + if full_x and full_y: + # If all corners are joined, that is a circle + return self.ellipse(xy, fill, outline, width) + + if d == 0 or not any(corners): + # If the corners have no curve, + # or there are no corners, + # that is a rectangle return self.rectangle(xy, fill, outline, width) r = d // 2 @@ -338,12 +346,17 @@ def draw_corners(pieslice): ) else: # Draw four separate corners - parts = ( - ((x1 - d, y0, x1, y0 + d), 270, 360), - ((x1 - d, y1 - d, x1, y1), 0, 90), - ((x0, y1 - d, x0 + d, y1), 90, 180), - ((x0, y0, x0 + d, y0 + d), 180, 270), - ) + parts = [] + for i, part in enumerate( + ( + ((x0, y0, x0 + d, y0 + d), 180, 270), + ((x1 - d, y0, x1, y0 + d), 270, 360), + ((x1 - d, y1 - d, x1, y1), 0, 90), + ((x0, y1 - d, x0 + d, y1), 90, 180), + ) + ): + if corners[i]: + parts.append(part) for part in parts: if pieslice: self.draw.draw_pieslice(*(part + (fill, 1))) @@ -358,25 +371,50 @@ def draw_corners(pieslice): else: self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill, 1) if not full_x and not full_y: - self.draw.draw_rectangle((x0, y0 + r + 1, x0 + r, y1 - r - 1), fill, 1) - self.draw.draw_rectangle((x1 - r, y0 + r + 1, x1, y1 - r - 1), fill, 1) + left = [x0, y0, x0 + r, y1] + if corners[0]: + left[1] += r + 1 + if corners[3]: + left[3] -= r + 1 + self.draw.draw_rectangle(left, fill, 1) + + right = [x1 - r, y0, x1, y1] + if corners[1]: + right[1] += r + 1 + if corners[2]: + right[3] -= r + 1 + self.draw.draw_rectangle(right, fill, 1) if ink is not None and ink != fill and width != 0: draw_corners(False) if not full_x: - self.draw.draw_rectangle( - (x0 + r + 1, y0, x1 - r - 1, y0 + width - 1), ink, 1 - ) - self.draw.draw_rectangle( - (x0 + r + 1, y1 - width + 1, x1 - r - 1, y1), ink, 1 - ) + top = [x0, y0, x1, y0 + width - 1] + if corners[0]: + top[0] += r + 1 + if corners[1]: + top[2] -= r + 1 + self.draw.draw_rectangle(top, ink, 1) + + bottom = [x0, y1 - width + 1, x1, y1] + if corners[3]: + bottom[0] += r + 1 + if corners[2]: + bottom[2] -= r + 1 + self.draw.draw_rectangle(bottom, ink, 1) if not full_y: - self.draw.draw_rectangle( - (x0, y0 + r + 1, x0 + width - 1, y1 - r - 1), ink, 1 - ) - self.draw.draw_rectangle( - (x1 - width + 1, y0 + r + 1, x1, y1 - r - 1), ink, 1 - ) + left = [x0, y0, x0 + width - 1, y1] + if corners[0]: + left[1] += r + 1 + if corners[3]: + left[3] -= r + 1 + self.draw.draw_rectangle(left, ink, 1) + + right = [x1 - width + 1, y0, x1, y1] + if corners[1]: + right[1] += r + 1 + if corners[2]: + right[3] -= r + 1 + self.draw.draw_rectangle(right, ink, 1) def _multiline_check(self, text): """Draw text."""
diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_nnnn.png b/Tests/images/imagedraw_rounded_rectangle_corners_nnnn.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_nnnn.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_nnny.png b/Tests/images/imagedraw_rounded_rectangle_corners_nnny.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_nnny.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_nnyn.png b/Tests/images/imagedraw_rounded_rectangle_corners_nnyn.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_nnyn.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_nnyy.png b/Tests/images/imagedraw_rounded_rectangle_corners_nnyy.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_nnyy.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_nynn.png b/Tests/images/imagedraw_rounded_rectangle_corners_nynn.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_nynn.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_nyny.png b/Tests/images/imagedraw_rounded_rectangle_corners_nyny.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_nyny.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_nyyn.png b/Tests/images/imagedraw_rounded_rectangle_corners_nyyn.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_nyyn.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_nyyy.png b/Tests/images/imagedraw_rounded_rectangle_corners_nyyy.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_nyyy.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_ynnn.png b/Tests/images/imagedraw_rounded_rectangle_corners_ynnn.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_ynnn.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_ynny.png b/Tests/images/imagedraw_rounded_rectangle_corners_ynny.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_ynny.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_ynyn.png b/Tests/images/imagedraw_rounded_rectangle_corners_ynyn.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_ynyn.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_ynyy.png b/Tests/images/imagedraw_rounded_rectangle_corners_ynyy.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_ynyy.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_yynn.png b/Tests/images/imagedraw_rounded_rectangle_corners_yynn.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_yynn.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_yyny.png b/Tests/images/imagedraw_rounded_rectangle_corners_yyny.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_yyny.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_yyyn.png b/Tests/images/imagedraw_rounded_rectangle_corners_yyyn.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_yyyn.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_corners_yyyy.png b/Tests/images/imagedraw_rounded_rectangle_corners_yyyy.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_corners_yyyy.png differ diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -735,6 +735,36 @@ def test_rounded_rectangle(xy): assert_image_equal_tofile(im, "Tests/images/imagedraw_rounded_rectangle.png") +@pytest.mark.parametrize("top_left", (True, False)) +@pytest.mark.parametrize("top_right", (True, False)) +@pytest.mark.parametrize("bottom_right", (True, False)) +@pytest.mark.parametrize("bottom_left", (True, False)) +def test_rounded_rectangle_corners(top_left, top_right, bottom_right, bottom_left): + corners = (top_left, top_right, bottom_right, bottom_left) + + # Arrange + im = Image.new("RGB", (200, 200)) + draw = ImageDraw.Draw(im) + + # Act + draw.rounded_rectangle( + (10, 20, 190, 180), 30, fill="red", outline="green", width=5, corners=corners + ) + + # Assert + suffix = "".join( + ( + ("y" if top_left else "n"), + ("y" if top_right else "n"), + ("y" if bottom_right else "n"), + ("y" if bottom_left else "n"), + ) + ) + assert_image_equal_tofile( + im, "Tests/images/imagedraw_rounded_rectangle_corners_" + suffix + ".png" + ) + + @pytest.mark.parametrize( "xy, radius, type", [
Add a corners parameter for `ImageDraw.rounded_rectangle`? ### What's your feature request? To add an optional bool tuple parameter (`corners=(True, True, True, True)`), or 4 optional bool parameters (`top_left=True, top_right=True, ...`) describing which corners of a rectangle should be rounded for `ImageDraw.rounded_rectangle` and possibly similar functions. ### What are your OS, Python and Pillow versions? * OS: Windows 10 * Python: 3.10.10 * Pillow: latest ## Example of feature request ```python draw.rounded_rectangle((x0, y0, x1, y1), radius=4, fill = white, corners=(True, False, True, False)) # TL TR BL BR draw.rounded_rectangle((x0, y0, x1, y1), radius=4, fill=white, top_right=False, bottom_right=False) ```
2023-02-16T09:00:58Z
9.4
python-pillow/Pillow
6,890
python-pillow__Pillow-6890
[ "6882" ]
145b80be56e23b9bb464ea8d1b2dd28b71f5bd81
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -722,6 +722,8 @@ def load_byte(self, data, legacy_api=True): @_register_writer(1) # Basic type, except for the legacy API. def write_byte(self, data): + if isinstance(data, IFDRational): + data = int(data) if isinstance(data, int): data = bytes((data,)) return data
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py --- a/Tests/test_file_tiff_metadata.py +++ b/Tests/test_file_tiff_metadata.py @@ -202,14 +202,15 @@ def test_writing_other_types_to_ascii(value, expected, tmp_path): assert reloaded.tag_v2[271] == expected -def test_writing_int_to_bytes(tmp_path): +@pytest.mark.parametrize("value", (1, IFDRational(1))) +def test_writing_other_types_to_bytes(value, tmp_path): im = hopper() info = TiffImagePlugin.ImageFileDirectory_v2() tag = TiffTags.TAGS_V2[700] assert tag.type == TiffTags.BYTE - info[700] = 1 + info[700] = value out = str(tmp_path / "temp.tiff") im.save(out, tiffinfo=info)
Bug: TypeError exif_transpose() / exif.tobytes() Doing `PIL.ImageOps.exif_transpose(im)` for a .jpg I get this error: ```pytb File "C:\Python38\lib\site-packages\PIL\ImageOps.py", line 602, in exif_transpose transposed_image.info["exif"] = transposed_exif.tobytes() File "C:\Python38\lib\site-packages\PIL\Image.py", line 3628, in tobytes return b"Exif\x00\x00" + head + ifd.tobytes(offset) File "C:\Python38\lib\site-packages\PIL\TiffImagePlugin.py", line 878, in tobytes data = ifd.tobytes(offset) File "C:\Python38\lib\site-packages\PIL\TiffImagePlugin.py", line 887, in tobytes "<table: %d bytes>" % len(data) if len(data) >= 16 else str(values) TypeError: object of type 'IFDRational' has no len() ``` At post-mortem: ```pycon >>> PIL.__version__ '9.3.0' >>> data 2.2 >>> type(data) <class 'PIL.TiffImagePlugin.IFDRational'> >>> len(data) Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: object of type 'IFDRational' has no len() # stack frame `data = ifd.tobytes(offset)` >>> tag, value (34853, {5: 2.2, 6: 0.0}) # GPSInfo >>> type(value[5]) <class 'PIL.TiffImagePlugin.IFDRational'> # stack frame with image: >>> im.getexif()[274] # Orientation 6 ``` (Can't publish the image / exif unfortunately, but it should be clear whats going on: IFDRational in GPS exif tag fails to serialize to bytes)
So you've found an image where the [GPSAltitudeRef](https://www.awaresystems.be/imaging/tiff/tifftags/privateifd/gps/gpsaltituderef.html), which should either be a BYTE of 0 (meaning "above sea level") or 1 (meaning "below sea level"), is instead 2.2. Thanks for trying to be helpful in the absence of an image. Do you know what software created this image? Out of curiosity, would you also be able to let us know what is the value of `typ`? > Do you know what software created this image? Out of curiosity, would you also be able to let us know what is the value of `typ`? It seems to be directly from a phone camera (LG). `typ` and other locals(): ```pytb >>> im._exif.tobytes() Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "C:\Python38\lib\site-packages\PIL\Image.py", line 3628, in tobytes return b"Exif\x00\x00" + head + ifd.tobytes(offset) File "C:\Python38\lib\site-packages\PIL\TiffImagePlugin.py", line 878, in tobytes data = ifd.tobytes(offset) File "C:\Python38\lib\site-packages\PIL\TiffImagePlugin.py", line 887, in tobytes "<table: %d bytes>" % len(data) if len(data) >= 16 else str(values) TypeError: object of type 'IFDRational' has no len() >>> pm() DBPE>>> typ 1 DBPE>>> locals() {'self': <PIL.TiffImagePlugin.ImageFileDirectory_v2 object at 0x0000022405E20D30>, 'offset': 1328, 'result': b'\x00\x02', 'entries': [], 'stripoffsets': None, 'tag': 5, 'value': 2.2, 'typ': 1, 'is_ifd': False, 'values': (2.2,), 'data': 2.2, 'tagname': 'GPSAltitudeRef', 'typname': 'byte', 'msg': 'save: GPSAltitudeRef (5) - type: byte (1)'} DBPE>>> self.tagtype {5: 1, 6: 5} DBPE>>> self._write_dispatch[typ](self, *values) 2.2 DBPE>>> ``` The typ 1 seems to be forced by these lines in `_setitem()` while self.group is 34853: ```python info = TiffTags.lookup(tag, self.group) ... if info.type: self.tagtype[tag] = info.type ``` ( When the data is extracted the same lines were passed for that tag, but self.group then is None, thus auto detection as IFDRational and `self.tagtype == {5: 5, 6: 5}` )
2023-01-13T10:05:10Z
9.4
python-pillow/Pillow
6,852
python-pillow__Pillow-6852
[ "6844" ]
28b8b6088e1a9ab87b96d5d7edd7fcbc08a43ea7
diff --git a/src/PIL/QoiImagePlugin.py b/src/PIL/QoiImagePlugin.py new file mode 100644 --- /dev/null +++ b/src/PIL/QoiImagePlugin.py @@ -0,0 +1,105 @@ +# +# The Python Imaging Library. +# +# QOI support for PIL +# +# See the README file for information on usage and redistribution. +# + +import os + +from . import Image, ImageFile +from ._binary import i32be as i32 +from ._binary import o8 + + +def _accept(prefix): + return prefix[:4] == b"qoif" + + +class QoiImageFile(ImageFile.ImageFile): + format = "QOI" + format_description = "Quite OK Image" + + def _open(self): + if not _accept(self.fp.read(4)): + msg = "not a QOI file" + raise SyntaxError(msg) + + self._size = tuple(i32(self.fp.read(4)) for i in range(2)) + + channels = self.fp.read(1)[0] + self.mode = "RGB" if channels == 3 else "RGBA" + + self.fp.seek(1, os.SEEK_CUR) # colorspace + self.tile = [("qoi", (0, 0) + self._size, self.fp.tell(), None)] + + +class QoiDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def _add_to_previous_pixels(self, value): + self._previous_pixel = value + + r, g, b, a = value + hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + self._previously_seen_pixels[hash_value] = value + + def decode(self, buffer): + self._previously_seen_pixels = {} + self._previous_pixel = None + self._add_to_previous_pixels(b"".join(o8(i) for i in (0, 0, 0, 255))) + + data = bytearray() + bands = Image.getmodebands(self.mode) + while len(data) < self.state.xsize * self.state.ysize * bands: + byte = self.fd.read(1)[0] + if byte == 0b11111110: # QOI_OP_RGB + value = self.fd.read(3) + o8(255) + elif byte == 0b11111111: # QOI_OP_RGBA + value = self.fd.read(4) + else: + op = byte >> 6 + if op == 0: # QOI_OP_INDEX + op_index = byte & 0b00111111 + value = self._previously_seen_pixels.get(op_index, (0, 0, 0, 0)) + elif op == 1: # QOI_OP_DIFF + value = ( + (self._previous_pixel[0] + ((byte & 0b00110000) >> 4) - 2) + % 256, + (self._previous_pixel[1] + ((byte & 0b00001100) >> 2) - 2) + % 256, + (self._previous_pixel[2] + (byte & 0b00000011) - 2) % 256, + ) + value += (self._previous_pixel[3],) + elif op == 2: # QOI_OP_LUMA + second_byte = self.fd.read(1)[0] + diff_green = (byte & 0b00111111) - 32 + diff_red = ((second_byte & 0b11110000) >> 4) - 8 + diff_blue = (second_byte & 0b00001111) - 8 + + value = tuple( + (self._previous_pixel[i] + diff_green + diff) % 256 + for i, diff in enumerate((diff_red, 0, diff_blue)) + ) + value += (self._previous_pixel[3],) + elif op == 3: # QOI_OP_RUN + run_length = (byte & 0b00111111) + 1 + value = self._previous_pixel + if bands == 3: + value = value[:3] + data += value * run_length + continue + value = b"".join(o8(i) for i in value) + self._add_to_previous_pixels(value) + + if bands == 3: + value = value[:3] + data += value + self.set_as_raw(bytes(data)) + return -1, 0 + + +Image.register_open(QoiImageFile.format, QoiImageFile, _accept) +Image.register_decoder("qoi", QoiDecoder) +Image.register_extension(QoiImageFile.format, ".qoi") diff --git a/src/PIL/__init__.py b/src/PIL/__init__.py --- a/src/PIL/__init__.py +++ b/src/PIL/__init__.py @@ -59,6 +59,7 @@ "PngImagePlugin", "PpmImagePlugin", "PsdImagePlugin", + "QoiImagePlugin", "SgiImagePlugin", "SpiderImagePlugin", "SunImagePlugin",
diff --git a/Tests/images/hopper.qoi b/Tests/images/hopper.qoi new file mode 100644 Binary files /dev/null and b/Tests/images/hopper.qoi differ diff --git a/Tests/images/pil123rgba.qoi b/Tests/images/pil123rgba.qoi new file mode 100644 Binary files /dev/null and b/Tests/images/pil123rgba.qoi differ diff --git a/Tests/test_file_qoi.py b/Tests/test_file_qoi.py new file mode 100644 --- /dev/null +++ b/Tests/test_file_qoi.py @@ -0,0 +1,28 @@ +import pytest + +from PIL import Image, QoiImagePlugin + +from .helper import assert_image_equal_tofile, assert_image_similar_tofile + + +def test_sanity(): + with Image.open("Tests/images/hopper.qoi") as im: + assert im.mode == "RGB" + assert im.size == (128, 128) + assert im.format == "QOI" + + assert_image_equal_tofile(im, "Tests/images/hopper.png") + + with Image.open("Tests/images/pil123rgba.qoi") as im: + assert im.mode == "RGBA" + assert im.size == (162, 150) + assert im.format == "QOI" + + assert_image_similar_tofile(im, "Tests/images/pil123rgba.png", 0.03) + + +def test_invalid_file(): + invalid_file = "Tests/images/flower.jpg" + + with pytest.raises(SyntaxError): + QoiImagePlugin.QoiImageFile(invalid_file)
QOI support ### What did you do? Tried to open a QOI image ( https://qoiformat.org/ ) with Pillow (`Image.open("picture.qoi")`) The picture is in this zip file (a 2-seconds stick-man) : [picture.zip](https://github.com/python-pillow/Pillow/files/10327604/picture.zip) ### What did you expect to happen? I would love Pillow to recognize the file type and open the image. ### What actually happened? Pillow can't recognize the QOI format. ```python >>> from PIL import Image >>> Image.open("picture.qoi") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.10/site-packages/PIL/Image.py", line 3186, in open raise UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file 'picture.qoi' ``` ### What are your OS, Python and Pillow versions? * OS: Manjaro Linux * Python: 3.10.8 * Pillow: 9.3.0 ### To replicate ```python from PIL import Image Image.open("picture.qoi") ```
I would be happy to contribute to Pillow by implementing QOI support btw (if in scope of pillow) Thanks for the test image, that was a helpful reference point. I've created PR #6852 to add support for reading QOI images. Oh thanks, just had a look and this seems like a very clean implementation
2023-01-02T08:23:32Z
9.4
python-pillow/Pillow
6,830
python-pillow__Pillow-6830
[ "6537" ]
907d59753bdd66460f0bc73e6022352f5ff14591
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -65,21 +65,16 @@ def __getattr__(name): if name in categories: deprecate("Image categories", 10, "is_animated", plural=True) return categories[name] - elif name in ("NEAREST", "NONE"): - deprecate(name, 10, "Resampling.NEAREST or Dither.NONE") - return 0 old_resampling = { "LINEAR": "BILINEAR", "CUBIC": "BICUBIC", "ANTIALIAS": "LANCZOS", } if name in old_resampling: - deprecate(name, 10, f"Resampling.{old_resampling[name]}") + deprecate( + name, 10, f"{old_resampling[name]} or Resampling.{old_resampling[name]}" + ) return Resampling[old_resampling[name]] - for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize): - if name in enum.__members__: - deprecate(name, 10, f"{enum.__name__}.{name}") - return enum[name] msg = f"module '{__name__}' has no attribute '{name}'" raise AttributeError(msg) @@ -218,6 +213,12 @@ class Quantize(IntEnum): LIBIMAGEQUANT = 3 +module = sys.modules[__name__] +for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize): + for item in enum: + setattr(module, item.name, item.value) + + if hasattr(core, "DEFAULT_STRATEGY"): DEFAULT_STRATEGY = core.DEFAULT_STRATEGY FILTERED = core.FILTERED
diff --git a/Tests/test_image.py b/Tests/test_image.py --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -921,12 +921,7 @@ def test_categories_deprecation(self): with pytest.warns(DeprecationWarning): assert Image.CONTAINER == 2 - def test_constants_deprecation(self): - with pytest.warns(DeprecationWarning): - assert Image.NEAREST == 0 - with pytest.warns(DeprecationWarning): - assert Image.NONE == 0 - + def test_constants(self): with pytest.warns(DeprecationWarning): assert Image.LINEAR == Image.Resampling.BILINEAR with pytest.warns(DeprecationWarning): @@ -943,8 +938,7 @@ def test_constants_deprecation(self): Image.Quantize, ): for name in enum.__members__: - with pytest.warns(DeprecationWarning): - assert getattr(Image, name) == enum[name] + assert getattr(Image, name) == enum[name] @pytest.mark.parametrize( "path",
API changes for Resampling modes With Pillow 9.2.0, I get the following deprecation notice: ``` DeprecationWarning: BILINEAR is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.BILINEAR instead. ``` Is it really necessary to introduce this breaking API change? Can the old names not be kept for backwards compatibility? Thousands of repositories will need to update their code, wasting countless man-hours. You can get a rough idea on how many repositories are affected from the following two websites, which search a subset of GitHub repositories: * https://grep.app/search?q=Image.BILINEAR * https://sourcegraph.com/search?q=context:global+Image.BILINEAR&patternType=standard ```python from PIL import Image img = Image.new("RGB", (5, 5)) img.resize((7, 7), Image.BILINEAR) ```
To provide context, the deprecations being discussed were added in #5954. The intention was not to make an arbitrary change, but to make use of a newish Python language feature, enums. https://github.com/python-pillow/Pillow/pull/5954#issuecomment-1009970094 > Do we keep the old constants "forever"? > > Or do we want to deprecate the old constants and remove them in Pillow 10 (15 months' deprecation period)? They were first deprecated in Pillow 9.1.0 - https://pillow.readthedocs.io/en/stable/releasenotes/9.1.0.html#deprecations I think in the scheme of things, this is a very minor change for users to make when upgrading to a new version. In Javascript programming, I'm used to finding old npm packages abandoned and replaced with new ones, and in iOS programming, I'd be surprised if Apple went a year without changing any constants. If your argument is that Pillow is extremely widely used, I'll try and use [NumPy](https://github.com/numpy/numpy) as a point of reference. That is another Python library, downloaded twice as much as Pillow. In NumPy 1.20.0, they [deprecated a series of aliases](https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations). https://grep.app/search?q=np.int seems to show that at least 20 times the amount of code is affected by that compared to https://grep.app/search?q=Image.BILINEAR. I make this comment not in the interest of taking a stance, but in the interest of giving you a quick response. > In NumPy 1.20.0, they [deprecated a series of aliases](https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations). I believe that the argument for deprecating inbuilt types in NumPy is a bit stronger since it was know for a long time to be an actual problem https://github.com/numpy/numpy/pull/6103 > The intention was not to make an arbitrary change, but to make use of a newish Python language feature, enums. The usage of a new Python language feature does not sound like a very convincing argument to me. Also, it is not an argument for breaking backwards compatibility. > https://grep.app/search?q=np.int seems to show that at least 20 times the amount of code is affected by that compared to https://grep.app/search?q=Image.BILINEAR. Your query also includes the non-deprecated types like `np.int_` or `np.int32`. If you exclude those with a regular expression like https://grep.app/search?q=np%5C.int%5B%5E0-9%5Ec%5Ep%5D&regexp=true there are 10 times fewer hits than https://grep.app/search?q=Image.BILINEAR ~~While I agree with the change in general, may I ask: What were the reasons to only bump `pillow`'s minor version? Wouldn't, at least according to semver, a breaking API change of such a widely used feature would justify a new major release?~~ Oh, scrape that, it was just introduced a deprecation warning so far. Everything good ;-) The deprecation warning may have appeared in a minor version, but the removal of the original values won't happen until the next major version. I'm having second thoughts about this API change. While enums are useful for this, and would be great for new things, I think this might be a bit too disruptive given the gains. It would be good to avoid a situation like the `PILLOW_VERSION` change as mentioned in https://github.com/python-pillow/Pillow/issues/6614#issuecomment-1256863816. What are other's thoughts? (As an aside, I wouldn't be averse to re-adding `PILLOW_VERSION`, it's just a constant; for example, it could be commented as deprecated with no warnings.) `PILLOW_VERSION` was deprecated in 5.2.0, removed in 7.0.0, restored as deprecated in 7.1.0 and removed again in 9.0.0. Fully restoring it may well help people on a practical level, but as an end user, I would feel very unsure about whether `PILLOW_VERSION` will be present or not in any future version of Pillow. I don't have strong feeling on what the implementation is, only a preference that we aim to be consistent - if a decision is made, that we follow through. For a different example, I'm reluctant about #5309 because we previously [told users to use `close()` to close files](https://pillow.readthedocs.io/en/stable/releasenotes/7.0.0.html#image-del), but that issue would like to prevent that behaviour. I think clear communication and expectations are more fundamental than backwards compatibility. > `PILLOW_VERSION` was deprecated in 5.2.0, removed in 7.0.0, restored as deprecated in 7.1.0 and removed again in 9.0.0. Fully restoring it may well help people on a practical level, but as an end user, I would feel very unsure about whether `PILLOW_VERSION` will be present or not in any future version of Pillow. I think that would be fine: the message is end users should not use `PILLOW_VERSION`. We'd comment it as deprecated, no removal date listed. Anyone accessing `PILLOW_VERSION` via legacy code (often as a dependency as a dependency) won't know either way. Anyone writing new code who looks it up and sees the comment should use `__version__` instead. But if they still use (e.g. by using autocomplete), it doesn't really matter. It's just a single constant, very little cost to leave it there than worry about removal. > I don't have strong feeling on what the implementation is, only a preference that we aim to be consistent - if a decision is made, that we follow through. For a different example, I'm reluctant about #5309 because we previously [told users to use `close()` to close files](https://pillow.readthedocs.io/en/stable/releasenotes/7.0.0.html#image-del), but that issue would like to prevent that behaviour. I think clear communication and expectations are more fundamental than backwards compatibility. I think we can change our minds, but should do so with clear communication. We need to balance cost/benefits of BC breaks, and it would be better to do so before release (both as `PILLOW_VERSION` taught us). Here's a PR to revert in case we want to go ahead: https://github.com/python-pillow/Pillow/pull/6684 I closed PR #6684, I somehow had glossed over that the enums were already released in 9.1.0, so this itself would be a breaking change. Some other ideas we're considering: * Keep the enums and deprecated ints * Keep the enums and deprecated ints, but extend deprecation period (e.g. from v10/July 2023 to v11/Oct 2024, or even without advertising an end date) * Provide API via both ints and enums, remove int deprecations
2022-12-27T22:45:31Z
9.3
python-pillow/Pillow
6,819
python-pillow__Pillow-6819
[ "6804" ]
edcfe09f12d6113aaca3a4b3f9bad343c0ddbdb9
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -1383,7 +1383,7 @@ def _save(im, fp, filename, chunk=putchunk, save_all=False): chunks.remove(cid) chunk(fp, cid, data) - exif = im.encoderinfo.get("exif", im.info.get("exif")) + exif = im.encoderinfo.get("exif") if exif: if isinstance(exif, Image.Exif): exif = exif.tobytes(8)
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -706,10 +706,18 @@ def test_exif(self): assert exif[274] == 3 def test_exif_save(self, tmp_path): + # Test exif is not saved from info + test_file = str(tmp_path / "temp.png") with Image.open("Tests/images/exif.png") as im: - test_file = str(tmp_path / "temp.png") im.save(test_file) + with Image.open(test_file) as reloaded: + assert reloaded._getexif() is None + + # Test passing in exif + with Image.open("Tests/images/exif.png") as im: + im.save(test_file, exif=im.getexif()) + with Image.open(test_file) as reloaded: exif = reloaded._getexif() assert exif[274] == 1 @@ -720,7 +728,7 @@ def test_exif_save(self, tmp_path): def test_exif_from_jpg(self, tmp_path): with Image.open("Tests/images/pil_sample_rgb.jpg") as im: test_file = str(tmp_path / "temp.png") - im.save(test_file) + im.save(test_file, exif=im.getexif()) with Image.open(test_file) as reloaded: exif = reloaded._getexif()
Exif information not saved in JPEG Plugin unless explicitly added in save call <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? Open an image, edit it's exif information, save the image and check the metadata. ### What did you expect to happen? I expected the modified exif information to be written. This is exactly what happend when saving the image as a `png`. ### What actually happened? The exif information was not saved when using the `jpg` format. It works when explicitly adding the `exif` parameter to the `save` call but this requires adding the exif information everywhere `save` is called (potentially third party code). This also means that exif information contained in the original image will be removed by loading and saving a JPEG image using PIL. If this is desired the PNG plugin should probably be modified to handle exif information in the same manner as the JPEG plugin, but for my usecase I prefer the way it is handled in PNG. ### What are your OS, Python and Pillow versions? * OS: Arch Linux with Kernel 6.0.6 * Python: 3.10.8 * Pillow: 9.4.0.dev0 (current main branch) ```python from PIL import Image from PIL import ExifTags desc = "My image description" exif_tag = ExifTags.Base.ImageDescription img = Image.open("hopper.jpg") exif = Image.Exif() exif[exif_tag] = "My image description" img.info["exif"] = exif # png plugin does save exif information img.save("hopper_out.png") png_exif = Image.open("hopper_out.png").getexif() assert png_exif != {} assert png_exif[exif_tag] == desc # jpeg plugin does not save exif information img.save("hopper_out.jpg") jpg_exif = Image.open("hopper_out.jpg").getexif() assert jpg_exif != {} assert jpg_exif[exif_tag] == desc ```
2022-12-23T01:16:13Z
9.3
python-pillow/Pillow
6,783
python-pillow__Pillow-6783
[ "6751" ]
f0b494ede583d9080548cc6d589bb376053ca93b
diff --git a/src/PIL/ImageGrab.py b/src/PIL/ImageGrab.py --- a/src/PIL/ImageGrab.py +++ b/src/PIL/ImageGrab.py @@ -132,4 +132,18 @@ def grabclipboard(): return BmpImagePlugin.DibImageFile(data) return None else: - raise NotImplementedError("ImageGrab.grabclipboard() is macOS and Windows only") + if shutil.which("wl-paste"): + args = ["wl-paste"] + elif shutil.which("xclip"): + args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"] + else: + raise NotImplementedError( + "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux" + ) + fh, filepath = tempfile.mkstemp() + subprocess.call(args, stdout=fh) + os.close(fh) + im = Image.open(filepath) + im.load() + os.unlink(filepath) + return im
diff --git a/Tests/test_imagegrab.py b/Tests/test_imagegrab.py --- a/Tests/test_imagegrab.py +++ b/Tests/test_imagegrab.py @@ -64,9 +64,13 @@ def test_grabclipboard(self): ) p.communicate() else: - with pytest.raises(NotImplementedError) as e: - ImageGrab.grabclipboard() - assert str(e.value) == "ImageGrab.grabclipboard() is macOS and Windows only" + if not shutil.which("wl-paste"): + with pytest.raises( + NotImplementedError, + match="wl-paste or xclip is required for" + r" ImageGrab.grabclipboard\(\) on Linux", + ): + ImageGrab.grabclipboard() return ImageGrab.grabclipboard()
Support ImageGrab from clipboard on Linux via xclip and wl-clipboard Currently, `grabclipboard` raises `NotImplementedError` on Linux. But I think we can use xclip or wl-clipboard if they are installed. A subprocess call saving the image to a temporary file should be enough. ```sh xclip -selection clipboard -t image/jpeg -o > test.jpg # Edit 1 wl-paste --type image/jpg > test.jpg ``` I'm willing to help implement this feature. ### What did you do? Try to grab an image from the clipboard on Linux ### What did you expect to happen? The image is grabbed ### What actually happened? ``` NotImplementedError: ImageGrab.grabclipboard() is macOS and Windows only ``` ### What are your OS, Python and Pillow versions? * OS: Linux (Manjaro KDE) * Python: 3.10.8 * Pillow: 9.3.0 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> ```python from PIL.ImageGrab import grabclipboard grabclipboard() ```
Considering that we support [`gnome-screenshot` in `ImageGrab.grab`](https://github.com/python-pillow/Pillow/blob/0ec32a30120cb22b533fd8563749d44bd5d3f78f/src/PIL/ImageGrab.py#L64-L75), this seems reasonable. I experimented with this, but found when I copied an image, `xclip` didn't work. https://user-images.githubusercontent.com/3112309/206149271-daab3ab1-854c-4a1a-b2c5-a93094fa329d.mov I have however created PR #6783 for `wl-paste`.
2022-12-07T10:30:11Z
9.3
python-pillow/Pillow
6,647
python-pillow__Pillow-6647
[ "6643" ]
243402e78e2bf2b7af478c6d891816e372b5c3f9
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1027,6 +1027,19 @@ def convert_transparency(m, v): warnings.warn("Couldn't allocate palette entry for transparency") return new + if "LAB" in (self.mode, mode): + other_mode = mode if self.mode == "LAB" else self.mode + if other_mode in ("RGB", "RGBA", "RGBX"): + from . import ImageCms + + srgb = ImageCms.createProfile("sRGB") + lab = ImageCms.createProfile("LAB") + profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] + transform = ImageCms.buildTransform( + profiles[0], profiles[1], self.mode, mode + ) + return transform.apply(self) + # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG
diff --git a/Tests/test_image_convert.py b/Tests/test_image_convert.py --- a/Tests/test_image_convert.py +++ b/Tests/test_image_convert.py @@ -242,6 +242,17 @@ def test_p2pa_palette(): assert im_pa.getpalette() == im.getpalette() +@pytest.mark.parametrize("mode", ("RGB", "RGBA", "RGBX")) +def test_rgb_lab(mode): + im = Image.new(mode, (1, 1)) + converted_im = im.convert("LAB") + assert converted_im.getpixel((0, 0)) == (0, 128, 128) + + im = Image.new("LAB", (1, 1), (255, 0, 0)) + converted_im = im.convert(mode) + assert converted_im.getpixel((0, 0))[:3] == (0, 255, 255) + + def test_matrix_illegal_conversion(): # Arrange im = hopper("CMYK")
convert("LAB") fails for RGB ### What did you do? Called PIL.Image.Image.convert(mode='LAB') for an RGB image ```python img = PIL.Image.open('filename.png').convert(mode='LAB') ``` ### What did you expect to happen? Conversion of data to LAB colourspace. ### What actually happened? ValueError: conversion from RGB to LAB not supported The following code did work: ```python rgb_lab_transform = PIL.ImageCms.buildTransformFromOpenProfiles(PIL.ImageCms.createProfile('sRGB'), PIL.ImageCms.createProfile('LAB'), 'RGB', 'LAB') img = PIL.ImageCms.applyTransform(Image.open('filename.png').convert(mode='RGB'), rgb_lab_transform) ``` ### What are your OS, Python and Pillow versions? * OS: Linux, kernel 5.15.32-gentoo-r1 * Python: 3.10.6 * Pillow: 9.2.0
2022-10-07T11:37:10Z
9.2
python-pillow/Pillow
6,582
python-pillow__Pillow-6582
[ "6580" ]
1d1a22bde37baaf162f4dd26e7b94cd96d3116a2
diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py --- a/src/PIL/WebPImagePlugin.py +++ b/src/PIL/WebPImagePlugin.py @@ -311,9 +311,11 @@ def _save(im, fp, filename): lossless = im.encoderinfo.get("lossless", False) quality = im.encoderinfo.get("quality", 80) icc_profile = im.encoderinfo.get("icc_profile") or "" - exif = im.encoderinfo.get("exif", "") + exif = im.encoderinfo.get("exif", b"") if isinstance(exif, Image.Exif): exif = exif.tobytes() + if exif.startswith(b"Exif\x00\x00"): + exif = exif[6:] xmp = im.encoderinfo.get("xmp", "") method = im.encoderinfo.get("method", 4)
diff --git a/Tests/test_file_webp_metadata.py b/Tests/test_file_webp_metadata.py --- a/Tests/test_file_webp_metadata.py +++ b/Tests/test_file_webp_metadata.py @@ -55,9 +55,7 @@ def test_write_exif_metadata(): test_buffer.seek(0) with Image.open(test_buffer) as webp_image: webp_exif = webp_image.info.get("exif", None) - assert webp_exif - if webp_exif: - assert webp_exif == expected_exif, "WebP EXIF didn't match" + assert webp_exif == expected_exif[6:], "WebP EXIF didn't match" def test_read_icc_profile():
EXIF prefix saved in WebP ### What did you do? I saved 2 copies of a webp file, one with exif=exif_bytes as shown, one without, then added the exif data by piexif.insert ### What did you expect to happen? exif data to be the same ### What actually happened? winmerge binary comparison reveals "Exif" is quoted one extra time in the Pillow image.save version indicating a coding error ### What are your OS, Python and Pillow versions? * OS: Windows 10 * Python: 3.8 * Pillow: 9.2.0 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> ```python from PIL import Image import piexif import piexif.helper info = "test data in User Comment" fullfn = "sample_image.webp" exif_bytes = piexif.dump({ "Exif": { piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(info, encoding="unicode") }, }) with Image.open(fullfn) as image: image.save(fullfn, quality=60, exif=exif_bytes) image.save("sample_image_inserted_exif.webp", "webp", quality=60) piexif.insert(exif_bytes, "sample_image_inserted_exif.webp") ```
2022-09-15T11:46:15Z
9.2
python-pillow/Pillow
6,517
python-pillow__Pillow-6517
[ "6515" ]
964e0aa0790a7d3d9dadb03b3045de6c7e124a6e
diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -482,8 +482,8 @@ def draw_text(ink, stroke_width=0, stroke_offset=None): # extract mask and set text alpha color, mask = mask, mask.getband(3) color.fillband(3, (ink >> 24) & 0xFF) - coord2 = coord[0] + mask.size[0], coord[1] + mask.size[1] - self.im.paste(color, coord + coord2, mask) + x, y = (int(c) for c in coord) + self.im.paste(color, (x, y, x + mask.size[0], y + mask.size[1]), mask) else: self.draw.draw_bitmap(coord, mask, ink)
diff --git a/Tests/images/text_float_coord.png b/Tests/images/text_float_coord.png new file mode 100644 Binary files /dev/null and b/Tests/images/text_float_coord.png differ diff --git a/Tests/images/text_float_coord_1_alt.png b/Tests/images/text_float_coord_1_alt.png new file mode 100644 Binary files /dev/null and b/Tests/images/text_float_coord_1_alt.png differ diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -935,7 +935,30 @@ def test_standard_embedded_color(layout_engine): d = ImageDraw.Draw(im) d.text((10, 10), txt, font=ttf, fill="#fa6", embedded_color=True) - assert_image_similar_tofile(im, "Tests/images/standard_embedded.png", 6.2) + assert_image_similar_tofile(im, "Tests/images/standard_embedded.png", 3.1) + + +@pytest.mark.parametrize("fontmode", ("1", "L", "RGBA")) +def test_float_coord(layout_engine, fontmode): + txt = "Hello World!" + ttf = ImageFont.truetype(FONT_PATH, 40, layout_engine=layout_engine) + + im = Image.new("RGB", (300, 64), "white") + d = ImageDraw.Draw(im) + if fontmode == "1": + d.fontmode = "1" + + embedded_color = fontmode == "RGBA" + d.text((9.5, 9.5), txt, font=ttf, fill="#fa6", embedded_color=embedded_color) + try: + assert_image_similar_tofile(im, "Tests/images/text_float_coord.png", 3.9) + except AssertionError: + if fontmode == "1" and layout_engine == ImageFont.Layout.BASIC: + assert_image_similar_tofile( + im, "Tests/images/text_float_coord_1_alt.png", 1 + ) + else: + raise def test_cbdt(layout_engine):
Can't use "align=center" together with "embedded_color=True" ### What did you do? ```python textwrapped = "Hello, world! 👋 Here are some emojis: 🎨 🌊 😎" font = ImageFont.truetype(THIS_FOLDER+"/fonts/seguiemj.ttf", font_size) //[merged font](https://github.com/thedemons/merge_color_emoji_font) d.text((int(qx),int(qy)), text=textwrapped, align="center", fill="#fff", font=font, embedded_color=True) ``` ### What did you expect to happen? center multiline text ### What actually happened? if i use "embedded_color=True" together with "align=center" i get this error: ``` d.text((int(qx),int(qy)), text=textwrapped, align="center", fill="#fff", font=font, embedded_color=True) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\ImageDraw.py", line 409, in text return self.multiline_text( File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\ImageDraw.py", line 563, in multiline_text self.text( File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\ImageDraw.py", line 498, in text draw_text(ink) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\ImageDraw.py", line 480, in draw_text self.im.paste(color, coord + coord2, mask) TypeError: 'float' object cannot be interpreted as an integer ``` **If i remove "align=center"** see here: https://imgur.com/a/rLnenPj - embedded color works fine: ![image](https://user-images.githubusercontent.com/1324225/185992808-717e6648-4f2b-426b-bfe6-06372106f871.png) **If i remove "embedded_color=True"** see here: https://imgur.com/a/Exq6aYe - align center works fine: ![image](https://user-images.githubusercontent.com/1324225/185992847-f2d74871-c309-4dcb-bc32-ebc0c20da07b.png) **but they cant work together.** ### What are your OS, Python and Pillow versions? * OS: Windows 10 * Python: 3.10 * Pillow: 9.2
2022-08-22T02:43:44Z
9.2
python-pillow/Pillow
6,500
python-pillow__Pillow-6500
[ "6572" ]
92b0f2c919897713bde2860a5fd13e3ca333c6e8
diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -375,6 +375,16 @@ def _save(im, fp, filename, bitmap_header=True): header = 40 # or 64 for OS/2 version 2 image = stride * im.size[1] + if im.mode == "1": + palette = b"".join(o8(i) * 4 for i in (0, 255)) + elif im.mode == "L": + palette = b"".join(o8(i) * 4 for i in range(256)) + elif im.mode == "P": + palette = im.im.getpalette("RGB", "BGRX") + colors = len(palette) // 4 + else: + palette = None + # bitmap header if bitmap_header: offset = 14 + header + colors * 4 @@ -405,14 +415,8 @@ def _save(im, fp, filename, bitmap_header=True): fp.write(b"\0" * (header - 40)) # padding (for OS/2 format) - if im.mode == "1": - for i in (0, 255): - fp.write(o8(i) * 4) - elif im.mode == "L": - for i in range(256): - fp.write(o8(i) * 4) - elif im.mode == "P": - fp.write(im.im.getpalette("RGB", "BGRX")) + if palette: + fp.write(palette) ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))]) diff --git a/src/PIL/TgaImagePlugin.py b/src/PIL/TgaImagePlugin.py --- a/src/PIL/TgaImagePlugin.py +++ b/src/PIL/TgaImagePlugin.py @@ -193,9 +193,10 @@ def _save(im, fp, filename): warnings.warn("id_section has been trimmed to 255 characters") if colormaptype: - colormapfirst, colormaplength, colormapentry = 0, 256, 24 + palette = im.im.getpalette("RGB", "BGR") + colormaplength, colormapentry = len(palette) // 3, 24 else: - colormapfirst, colormaplength, colormapentry = 0, 0, 0 + colormaplength, colormapentry = 0, 0 if im.mode in ("LA", "RGBA"): flags = 8 @@ -210,7 +211,7 @@ def _save(im, fp, filename): o8(id_len) + o8(colormaptype) + o8(imagetype) - + o16(colormapfirst) + + o16(0) # colormapfirst + o16(colormaplength) + o8(colormapentry) + o16(0) @@ -225,7 +226,7 @@ def _save(im, fp, filename): fp.write(id_section) if colormaptype: - fp.write(im.im.getpalette("RGB", "BGR")) + fp.write(palette) if rle: ImageFile._save(
diff --git a/Tests/test_file_bmp.py b/Tests/test_file_bmp.py --- a/Tests/test_file_bmp.py +++ b/Tests/test_file_bmp.py @@ -51,6 +51,18 @@ def test_save_to_bytes(): assert reloaded.format == "BMP" +def test_small_palette(tmp_path): + im = Image.new("P", (1, 1)) + colors = [0, 0, 0, 125, 125, 125, 255, 255, 255] + im.putpalette(colors) + + out = str(tmp_path / "temp.bmp") + im.save(out) + + with Image.open(out) as reloaded: + assert reloaded.getpalette() == colors + + def test_save_too_large(tmp_path): outfile = str(tmp_path / "temp.bmp") with Image.new("RGB", (1, 1)) as im: diff --git a/Tests/test_file_tga.py b/Tests/test_file_tga.py --- a/Tests/test_file_tga.py +++ b/Tests/test_file_tga.py @@ -123,6 +123,18 @@ def test_save(tmp_path): assert test_im.size == (100, 100) +def test_small_palette(tmp_path): + im = Image.new("P", (1, 1)) + colors = [0, 0, 0] + im.putpalette(colors) + + out = str(tmp_path / "temp.tga") + im.save(out) + + with Image.open(out) as reloaded: + assert reloaded.getpalette() == colors + + def test_save_wrong_mode(tmp_path): im = hopper("PA") out = str(tmp_path / "temp.tga")
Invalid 8-bit BMP files written when not all palette colours are used ### What did you do? I loaded an image (BMP or PNG) in 8-bit format. (i.e. with a palette of up to 256 colours) The image did use a palette with _less than_ 256 colours. Then I edited the image and saved it again, as 8-bit BMP. EDIT: This may be a similar problem as #6500. ### What did you expect to happen? The saved image should be viewable by Windows' default image viewer. ### What actually happened? The saved image was corrupt and could not be displayed. Reason: The offset calculation for the `bfSize` (file offset 0x02) and `bfOffBits` (file offset 0x0A) assumes that the palette is 256 colours large (0x400 bytes). However there are only 0x200 bytes written for the palette. (4 bytes * 128 colours) The fields `biClrUsed` (file offset 0x2E) and `biClrImportant` (file offset 0x32) are also incorrectly set to 256 instead of 128. ### What are your OS, Python and Pillow versions? * OS: Windows 10 1909 * Python: Python 3.7.6 * Pillow: 9.2.0 I attached an archive with two tests: [bmp-tests.zip](https://github.com/python-pillow/Pillow/files/9551375/bmp-tests.zip) - Test 1: BMP image with 256 colours being used (works fine) - Test 2: BMP image with 128 colours being used (broken after resaving) ```python import PIL.Image with PIL.Image.open("Test1_AllColors.bmp") as img1: img1.save("t1-good.bmp") with PIL.Image.open("Test2_128Colors.bmp") as img2: img2.save("t2-bad.bmp") ```
2022-08-13T09:53:12Z
9.2
python-pillow/Pillow
6,481
python-pillow__Pillow-6481
[ "6387" ]
1b5abea0431b6ea2f111a5f72a8f25a1af397490
diff --git a/src/PIL/PsdImagePlugin.py b/src/PIL/PsdImagePlugin.py --- a/src/PIL/PsdImagePlugin.py +++ b/src/PIL/PsdImagePlugin.py @@ -75,6 +75,9 @@ def _open(self): if channels > psd_channels: raise OSError("not enough channels") + if mode == "RGB" and psd_channels == 4: + mode = "RGBA" + channels = 4 self.mode = mode self._size = i32(s, 18), i32(s, 14)
diff --git a/Tests/images/rgba.psd b/Tests/images/rgba.psd new file mode 100644 Binary files /dev/null and b/Tests/images/rgba.psd differ diff --git a/Tests/test_file_psd.py b/Tests/test_file_psd.py --- a/Tests/test_file_psd.py +++ b/Tests/test_file_psd.py @@ -4,7 +4,7 @@ from PIL import Image, PsdImagePlugin -from .helper import assert_image_similar, hopper, is_pypy +from .helper import assert_image_equal_tofile, assert_image_similar, hopper, is_pypy test_file = "Tests/images/hopper.psd" @@ -107,6 +107,11 @@ def test_open_after_exclusive_load(): im.load() +def test_rgba(): + with Image.open("Tests/images/rgba.psd") as im: + assert_image_equal_tofile(im, "Tests/images/imagedraw_square.png") + + def test_icc_profile(): with Image.open(test_file) as im: assert "icc_profile" in im.info
PSD incorrectly loaded ### What did you do? I opened the TIFF in Pillow and converted it to JPG. ### What did you expect to happen? The JPG image to look the same as the original TIFF. ### What actually happened? The converted JPG looks malformed and has messed up colors. ### What are your OS, Python and Pillow versions? * OS: Linux * Python: 3.10.5 * Pillow: 9.1.1 (also tested -git) ```python >>> img = Image.open("3662b8bd397337482862ab1a06bf3366-OA_535_161_17_F_TE.tif") >>> out_img = img.convert("RGB") >>> out_img.save("converted.jpg", quality=95) ``` [original image](https://api.collectie.gent/storage/v1/download/3662b8bd397337482862ab1a06bf3366-OA_535_161_17_F_TE.tif) (beware, 274MB) [converted image](https://api.collectie.gent/storage/v1/download/3a029a4f48b480211286486a6a1f0f0b-transcode-OA_535_161_17_F_TE.jpg) Is it okay to report this here or should I report this to the appropriate library (libtiff, jpeg-turbo, ?)
Here is the right place to report it - taking a look, your file is actually not a TIFF, but a Photoshop file. The fact that we're not loading it correctly has nothing to do with those other libraries. @radarhere My bad, I should have checked the mimetype...
2022-08-05T13:43:28Z
9.2
python-pillow/Pillow
6,431
python-pillow__Pillow-6431
[ "6430" ]
4db2ed3a6f330efcb66c9b6f36cc668a913d371c
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -509,6 +509,10 @@ def chunk_sRGB(self, pos, length): # 3 absolute colorimetric s = ImageFile._safe_read(self.fp, length) + if length < 1: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + raise ValueError("Truncated sRGB chunk") self.im_info["srgb"] = s[0] return s
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -635,7 +635,9 @@ def test_padded_idat(self): assert_image_equal_tofile(im, "Tests/images/bw_gradient.png") - @pytest.mark.parametrize("cid", (b"IHDR", b"pHYs", b"acTL", b"fcTL", b"fdAT")) + @pytest.mark.parametrize( + "cid", (b"IHDR", b"sRGB", b"pHYs", b"acTL", b"fcTL", b"fdAT") + ) def test_truncated_chunks(self, cid): fp = BytesIO() with PngImagePlugin.PngStream(fp) as png:
[PNG] IndexError is raised when the sRGB chunk is broken ### What did you do? ```python3 from PIL import Image import io # assumes the current directory is the root of this repository. with open('Tests/images/imagedraw_polygon_1px_high.png', 'rb') as f: data = bytearray(f.read()) # insert the sRGB chunk after the IDAT chunk. Its length, chunk type and crc are valid, but the sRGB chunk should contain more data. data[61:61] = b"\x00\x00\x00\x00sRGB\x10\x1c\xd3\xce" # IndexError is raised with Image.open(io.BytesIO(data)) as img: img.load() ``` ### What did you expect to happen? IndexError is a little conusing. Maybe ValueError is better. ### What actually happened? ``` Traceback (most recent call last): File "issue_index_error_simplified.py", line 14, in <module> img.load() File "/usr/local/lib/python3.8/dist-packages/PIL/ImageFile.py", line 268, in load self.load_end() File "/usr/local/lib/python3.8/dist-packages/PIL/PngImagePlugin.py", line 978, in load_end self.png.call(cid, pos, length) File "/usr/local/lib/python3.8/dist-packages/PIL/PngImagePlugin.py", line 202, in call return getattr(self, "chunk_" + cid.decode("ascii"))(pos, length) File "/usr/local/lib/python3.8/dist-packages/PIL/PngImagePlugin.py", line 512, in chunk_sRGB self.im_info["srgb"] = s[0] IndexError: index out of range ``` ### What are your OS, Python and Pillow versions? * OS: ubuntu:focal-20220426 * Python: 3.8.10 * Pillow: 9.2.0
2022-07-11T10:05:05Z
9.2
python-pillow/Pillow
6,381
python-pillow__Pillow-6381
[ "5816" ]
11918eac0628ec8ac0812670d9838361ead2d6a4
diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -32,8 +32,10 @@ import math import numbers +import warnings from . import Image, ImageColor +from ._deprecate import deprecate """ A simple 2D drawing interface for PIL images. @@ -372,6 +374,19 @@ def _multiline_split(self, text): return text.split(split_character) + def _multiline_spacing(self, font, spacing, stroke_width): + # this can be replaced with self.textbbox(...)[3] when textsize is removed + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + return ( + self.textsize( + "A", + font=font, + stroke_width=stroke_width, + )[1] + + spacing + ) + def text( self, xy, @@ -511,9 +526,7 @@ def multiline_text( widths = [] max_width = 0 lines = self._multiline_split(text) - line_spacing = ( - self.textsize("A", font=font, stroke_width=stroke_width)[1] + spacing - ) + line_spacing = self._multiline_spacing(font, spacing, stroke_width) for line in lines: line_width = self.textlength( line, font, direction=direction, features=features, language=language @@ -573,14 +586,31 @@ def textsize( stroke_width=0, ): """Get the size of a given string, in pixels.""" + deprecate("textsize", 10, "textbbox or textlength") if self._multiline_check(text): - return self.multiline_textsize( - text, font, spacing, direction, features, language, stroke_width - ) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + return self.multiline_textsize( + text, + font, + spacing, + direction, + features, + language, + stroke_width, + ) if font is None: font = self.getfont() - return font.getsize(text, direction, features, language, stroke_width) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + return font.getsize( + text, + direction, + features, + language, + stroke_width, + ) def multiline_textsize( self, @@ -592,16 +622,23 @@ def multiline_textsize( language=None, stroke_width=0, ): + deprecate("multiline_textsize", 10, "multiline_textbbox") max_width = 0 lines = self._multiline_split(text) - line_spacing = ( - self.textsize("A", font=font, stroke_width=stroke_width)[1] + spacing - ) - for line in lines: - line_width, line_height = self.textsize( - line, font, spacing, direction, features, language, stroke_width - ) - max_width = max(max_width, line_width) + line_spacing = self._multiline_spacing(font, spacing, stroke_width) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + for line in lines: + line_width, line_height = self.textsize( + line, + font, + spacing, + direction, + features, + language, + stroke_width, + ) + max_width = max(max_width, line_width) return max_width, len(lines) * line_spacing - spacing def textlength( @@ -625,9 +662,16 @@ def textlength( try: return font.getlength(text, mode, direction, features, language) except AttributeError: - size = self.textsize( - text, font, direction=direction, features=features, language=language - ) + deprecate("textlength support for fonts without getlength", 10) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + size = self.textsize( + text, + font, + direction=direction, + features=features, + language=language, + ) if direction == "ttb": return size[1] return size[0] @@ -667,10 +711,6 @@ def textbbox( if font is None: font = self.getfont() - from . import ImageFont - - if not isinstance(font, ImageFont.FreeTypeFont): - raise ValueError("Only supported for TrueType fonts") mode = "RGBA" if embedded_color else self.fontmode bbox = font.getbbox( text, mode, direction, features, language, stroke_width, anchor @@ -704,9 +744,7 @@ def multiline_textbbox( widths = [] max_width = 0 lines = self._multiline_split(text) - line_spacing = ( - self.textsize("A", font=font, stroke_width=stroke_width)[1] + spacing - ) + line_spacing = self._multiline_spacing(font, spacing, stroke_width) for line in lines: line_width = self.textlength( line, diff --git a/src/PIL/ImageDraw2.py b/src/PIL/ImageDraw2.py --- a/src/PIL/ImageDraw2.py +++ b/src/PIL/ImageDraw2.py @@ -24,7 +24,10 @@ """ +import warnings + from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath +from ._deprecate import deprecate class Pen: @@ -172,8 +175,35 @@ def text(self, xy, text, font): def textsize(self, text, font): """ + .. deprecated:: 9.2.0 + Return the size of the given string, in pixels. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textsize` """ - return self.draw.textsize(text, font=font.font) + deprecate("textsize", 10, "textbbox or textlength") + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + return self.draw.textsize(text, font=font.font) + + def textbbox(self, xy, text, font): + """ + Returns bounding box (in pixels) of given text. + + :return: ``(left, top, right, bottom)`` bounding box + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox` + """ + if self.transform: + xy = ImagePath.Path(xy) + xy.transform(self.transform) + return self.draw.textbbox(xy, text, font=font.font) + + def textlength(self, text, font): + """ + Returns length (in pixels) of given text. + This is the amount by which following text should be offset. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength` + """ + return self.draw.textlength(text, font=font.font) diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -137,12 +137,17 @@ def _load_pilfont_data(self, file, image): def getsize(self, text, *args, **kwargs): """ + .. deprecated:: 9.2.0 + + Use :py:meth:`.getbbox` or :py:meth:`.getlength` instead. + Returns width and height (in pixels) of given text. :param text: Text to measure. :return: (width, height) """ + deprecate("getsize", 10, "getbbox or getlength") return self.font.getsize(text) def getmask(self, text, mode="", *args, **kwargs): @@ -165,6 +170,33 @@ def getmask(self, text, mode="", *args, **kwargs): """ return self.font.getmask(text, mode) + def getbbox(self, text, *args, **kwargs): + """ + Returns bounding box (in pixels) of given text. + + .. versionadded:: 9.2.0 + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + :return: ``(left, top, right, bottom)`` bounding box + """ + width, height = self.font.getsize(text) + return 0, 0, width, height + + def getlength(self, text, *args, **kwargs): + """ + Returns length (in pixels) of given text. + This is the amount by which following text should be offset. + + .. versionadded:: 9.2.0 + """ + width, height = self.font.getsize(text) + return width + ## # Wrapper for FreeType fonts. Application code should use the @@ -386,16 +418,23 @@ def getbbox( return left, top, left + width, top + height def getsize( - self, text, direction=None, features=None, language=None, stroke_width=0 + self, + text, + direction=None, + features=None, + language=None, + stroke_width=0, ): """ - Returns width and height (in pixels) of given text if rendered in font with - provided direction, features, and language. + .. deprecated:: 9.2.0 Use :py:meth:`getlength()` to measure the offset of following text with 1/64 pixel precision. Use :py:meth:`getbbox()` to get the exact bounding box based on an anchor. + Returns width and height (in pixels) of given text if rendered in font with + provided direction, features, and language. + .. note:: For historical reasons this function measures text height from the ascender line instead of the top, see :ref:`text-anchors`. If you wish to measure text height from the top, it is recommended @@ -438,6 +477,7 @@ def getsize( :return: (width, height) """ + deprecate("getsize", 10, "getbbox or getlength") # vertical offset is added for historical reasons # see https://github.com/python-pillow/Pillow/pull/4910#discussion_r486682929 size, offset = self.font.getsize(text, "L", direction, features, language) @@ -456,6 +496,10 @@ def getsize_multiline( stroke_width=0, ): """ + .. deprecated:: 9.2.0 + + Use :py:meth:`.ImageDraw.multiline_textbbox` instead. + Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language, while respecting newline characters. @@ -495,19 +539,26 @@ def getsize_multiline( :return: (width, height) """ + deprecate("getsize_multiline", 10, "ImageDraw.multiline_textbbox") max_width = 0 lines = self._multiline_split(text) - line_spacing = self.getsize("A", stroke_width=stroke_width)[1] + spacing - for line in lines: - line_width, line_height = self.getsize( - line, direction, features, language, stroke_width - ) - max_width = max(max_width, line_width) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + line_spacing = self.getsize("A", stroke_width=stroke_width)[1] + spacing + for line in lines: + line_width, line_height = self.getsize( + line, direction, features, language, stroke_width + ) + max_width = max(max_width, line_width) return max_width, len(lines) * line_spacing - spacing def getoffset(self, text): """ + .. deprecated:: 9.2.0 + + Use :py:meth:`.getbbox` instead. + Returns the offset of given text. This is the gap between the starting coordinate and the first marking. Note that this gap is included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`. @@ -516,6 +567,7 @@ def getoffset(self, text): :return: A tuple of the x and y offset """ + deprecate("getoffset", 10, "getbbox") return self.font.getsize(text)[1] def getmask( @@ -796,7 +848,15 @@ def __init__(self, font, orientation=None): self.orientation = orientation # any 'transpose' argument, or None def getsize(self, text, *args, **kwargs): - w, h = self.font.getsize(text) + """ + .. deprecated:: 9.2.0 + + Use :py:meth:`.getbbox` or :py:meth:`.getlength` instead. + """ + deprecate("getsize", 10, "getbbox or getlength") + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + w, h = self.font.getsize(text) if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270): return h, w return w, h @@ -807,6 +867,23 @@ def getmask(self, text, mode="", *args, **kwargs): return im.transpose(self.orientation) return im + def getbbox(self, text, *args, **kwargs): + # TransposedFont doesn't support getmask2, move top-left point to (0, 0) + # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont + left, top, right, bottom = self.font.getbbox(text, *args, **kwargs) + width = right - left + height = bottom - top + if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270): + return 0, 0, height, width + return 0, 0, width, height + + def getlength(self, text, *args, **kwargs): + if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270): + raise ValueError( + "text length is undefined for text rotated by 90 or 270 degrees" + ) + return self.font.getlength(text, *args, **kwargs) + def load(filename): """
diff --git a/Tests/images/rectangle_surrounding_text.png b/Tests/images/rectangle_surrounding_text.png Binary files a/Tests/images/rectangle_surrounding_text.png and b/Tests/images/rectangle_surrounding_text.png differ diff --git a/Tests/oss-fuzz/fuzzers.py b/Tests/oss-fuzz/fuzzers.py --- a/Tests/oss-fuzz/fuzzers.py +++ b/Tests/oss-fuzz/fuzzers.py @@ -33,9 +33,9 @@ def fuzz_font(data): # different font objects. return - font.getsize_multiline("ABC\nAaaa") + font.getbbox("ABC") font.getmask("test text") with Image.new(mode="RGBA", size=(200, 200)) as im: draw = ImageDraw.Draw(im) - draw.multiline_textsize("ABC\nAaaa", font, stroke_width=2) + draw.multiline_textbbox((10, 10), "ABC\nAaaa", font, stroke_width=2) draw.text((10, 10), "Test Text", font=font, fill="#000") diff --git a/Tests/test_font_pcf.py b/Tests/test_font_pcf.py --- a/Tests/test_font_pcf.py +++ b/Tests/test_font_pcf.py @@ -76,12 +76,19 @@ def test_textsize(request, tmp_path): tempname = save_font(request, tmp_path) font = ImageFont.load(tempname) for i in range(255): - (dx, dy) = font.getsize(chr(i)) + (ox, oy, dx, dy) = font.getbbox(chr(i)) + assert ox == 0 + assert oy == 0 assert dy == 20 assert dx in (0, 10) + assert font.getlength(chr(i)) == dx + with pytest.warns(DeprecationWarning) as log: + assert font.getsize(chr(i)) == (dx, dy) + assert len(log) == 1 for i in range(len(message)): msg = message[: i + 1] - assert font.getsize(msg) == (len(msg) * 10, 20) + assert font.getlength(msg) == len(msg) * 10 + assert font.getbbox(msg) == (0, 0, len(msg) * 10, 20) def _test_high_characters(request, tmp_path, message): diff --git a/Tests/test_font_pcf_charsets.py b/Tests/test_font_pcf_charsets.py --- a/Tests/test_font_pcf_charsets.py +++ b/Tests/test_font_pcf_charsets.py @@ -101,13 +101,17 @@ def _test_textsize(request, tmp_path, encoding): tempname = save_font(request, tmp_path, encoding) font = ImageFont.load(tempname) for i in range(255): - (dx, dy) = font.getsize(bytearray([i])) + (ox, oy, dx, dy) = font.getbbox(bytearray([i])) + assert ox == 0 + assert oy == 0 assert dy == 20 assert dx in (0, 10) + assert font.getlength(bytearray([i])) == dx message = charsets[encoding]["message"].encode(encoding) for i in range(len(message)): msg = message[: i + 1] - assert font.getsize(msg) == (len(msg) * 10, 20) + assert font.getlength(msg) == len(msg) * 10 + assert font.getbbox(msg) == (0, 0, len(msg) * 10, 20) def test_textsize_iso8859_1(request, tmp_path): diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -1232,21 +1232,39 @@ def test_textsize_empty_string(): # Act # Should not cause 'SystemError: <built-in method getsize of # ImagingFont object at 0x...> returned NULL without setting an error' - draw.textsize("") - draw.textsize("\n") - draw.textsize("test\n") + draw.textbbox((0, 0), "") + draw.textbbox((0, 0), "\n") + draw.textbbox((0, 0), "test\n") + draw.textlength("") @skip_unless_feature("freetype2") -def test_textsize_stroke(): +def test_textbbox_stroke(): # Arrange im = Image.new("RGB", (W, H)) draw = ImageDraw.Draw(im) font = ImageFont.truetype("Tests/fonts/FreeMono.ttf", 20) # Act / Assert - assert draw.textsize("A", font, stroke_width=2) == (16, 20) - assert draw.multiline_textsize("ABC\nAaaa", font, stroke_width=2) == (52, 44) + assert draw.textbbox((2, 2), "A", font, stroke_width=2) == (0, 4, 16, 20) + assert draw.textbbox((2, 2), "A", font, stroke_width=4) == (-2, 2, 18, 22) + assert draw.textbbox((2, 2), "ABC\nAaaa", font, stroke_width=2) == (0, 4, 52, 44) + assert draw.textbbox((2, 2), "ABC\nAaaa", font, stroke_width=4) == (-2, 2, 54, 50) + + +def test_textsize_deprecation(): + im = Image.new("RGB", (W, H)) + draw = ImageDraw.Draw(im) + + with pytest.warns(DeprecationWarning) as log: + draw.textsize("Hello") + assert len(log) == 1 + with pytest.warns(DeprecationWarning) as log: + draw.textsize("Hello\nWorld") + assert len(log) == 1 + with pytest.warns(DeprecationWarning) as log: + draw.multiline_textsize("Hello\nWorld") + assert len(log) == 1 @skip_unless_feature("freetype2") diff --git a/Tests/test_imagedraw2.py b/Tests/test_imagedraw2.py --- a/Tests/test_imagedraw2.py +++ b/Tests/test_imagedraw2.py @@ -1,5 +1,7 @@ import os.path +import pytest + from PIL import Image, ImageDraw, ImageDraw2 from .helper import ( @@ -205,7 +207,9 @@ def test_textsize(): font = ImageDraw2.Font("white", FONT_PATH) # Act - size = draw.textsize("ImageDraw2", font) + with pytest.warns(DeprecationWarning) as log: + size = draw.textsize("ImageDraw2", font) + assert len(log) == 1 # Assert assert size[1] == 12 @@ -221,9 +225,10 @@ def test_textsize_empty_string(): # Act # Should not cause 'SystemError: <built-in method getsize of # ImagingFont object at 0x...> returned NULL without setting an error' - draw.textsize("", font) - draw.textsize("\n", font) - draw.textsize("test\n", font) + draw.textbbox((0, 0), "", font) + draw.textbbox((0, 0), "\n", font) + draw.textbbox((0, 0), "test\n", font) + draw.textlength("", font) @skip_unless_feature("freetype2") diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -94,7 +94,7 @@ def test_non_ascii_path(self, tmp_path): def _render(self, font): txt = "Hello World!" ttf = ImageFont.truetype(font, FONT_SIZE, layout_engine=self.LAYOUT_ENGINE) - ttf.getsize(txt) + ttf.getbbox(txt) img = Image.new("RGB", (256, 64), "white") d = ImageDraw.Draw(img) @@ -135,15 +135,15 @@ def test_I16(self): target = "Tests/images/transparent_background_text_L.png" assert_image_similar_tofile(im.convert("L"), target, 0.01) - def test_textsize_equal(self): + def test_textbbox_equal(self): im = Image.new(mode="RGB", size=(300, 100)) draw = ImageDraw.Draw(im) ttf = self.get_font() txt = "Hello World!" - size = draw.textsize(txt, ttf) + bbox = draw.textbbox((10, 10), txt, ttf) draw.text((10, 10), txt, font=ttf) - draw.rectangle((10, 10, 10 + size[0], 10 + size[1])) + draw.rectangle(bbox) assert_image_similar_tofile( im, "Tests/images/rectangle_surrounding_text.png", 2.5 @@ -184,7 +184,7 @@ def test_render_multiline(self): im = Image.new(mode="RGB", size=(300, 100)) draw = ImageDraw.Draw(im) ttf = self.get_font() - line_spacing = draw.textsize("A", font=ttf)[1] + 4 + line_spacing = ttf.getbbox("A")[3] + 4 lines = TEST_TEXT.split("\n") y = 0 for line in lines: @@ -245,19 +245,39 @@ def test_multiline_size(self): im = Image.new(mode="RGB", size=(300, 100)) draw = ImageDraw.Draw(im) - # Test that textsize() correctly connects to multiline_textsize() - assert draw.textsize(TEST_TEXT, font=ttf) == draw.multiline_textsize( - TEST_TEXT, font=ttf + with pytest.warns(DeprecationWarning) as log: + # Test that textsize() correctly connects to multiline_textsize() + assert draw.textsize(TEST_TEXT, font=ttf) == draw.multiline_textsize( + TEST_TEXT, font=ttf + ) + + # Test that multiline_textsize corresponds to ImageFont.textsize() + # for single line text + assert ttf.getsize("A") == draw.multiline_textsize("A", font=ttf) + + # Test that textsize() can pass on additional arguments + # to multiline_textsize() + draw.textsize(TEST_TEXT, font=ttf, spacing=4) + draw.textsize(TEST_TEXT, ttf, 4) + assert len(log) == 6 + + def test_multiline_bbox(self): + ttf = self.get_font() + im = Image.new(mode="RGB", size=(300, 100)) + draw = ImageDraw.Draw(im) + + # Test that textbbox() correctly connects to multiline_textbbox() + assert draw.textbbox((0, 0), TEST_TEXT, font=ttf) == draw.multiline_textbbox( + (0, 0), TEST_TEXT, font=ttf ) - # Test that multiline_textsize corresponds to ImageFont.textsize() + # Test that multiline_textbbox corresponds to ImageFont.textbbox() # for single line text - assert ttf.getsize("A") == draw.multiline_textsize("A", font=ttf) + assert ttf.getbbox("A") == draw.multiline_textbbox((0, 0), "A", font=ttf) - # Test that textsize() can pass on additional arguments - # to multiline_textsize() - draw.textsize(TEST_TEXT, font=ttf, spacing=4) - draw.textsize(TEST_TEXT, ttf, 4) + # Test that textbbox() can pass on additional arguments + # to multiline_textbbox() + draw.textbbox((0, 0), TEST_TEXT, font=ttf, spacing=4) def test_multiline_width(self): ttf = self.get_font() @@ -265,9 +285,15 @@ def test_multiline_width(self): draw = ImageDraw.Draw(im) assert ( - draw.textsize("longest line", font=ttf)[0] - == draw.multiline_textsize("longest line\nline", font=ttf)[0] + draw.textbbox((0, 0), "longest line", font=ttf)[2] + == draw.multiline_textbbox((0, 0), "longest line\nline", font=ttf)[2] ) + with pytest.warns(DeprecationWarning) as log: + assert ( + draw.textsize("longest line", font=ttf)[0] + == draw.multiline_textsize("longest line\nline", font=ttf)[0] + ) + assert len(log) == 2 def test_multiline_spacing(self): ttf = self.get_font() @@ -289,16 +315,33 @@ def test_rotated_transposed_font(self): # Original font draw.font = font - box_size_a = draw.textsize(word) + with pytest.warns(DeprecationWarning) as log: + box_size_a = draw.textsize(word) + assert box_size_a == font.getsize(word) + assert len(log) == 2 + bbox_a = draw.textbbox((10, 10), word) # Rotated font draw.font = transposed_font - box_size_b = draw.textsize(word) + with pytest.warns(DeprecationWarning) as log: + box_size_b = draw.textsize(word) + assert box_size_b == transposed_font.getsize(word) + assert len(log) == 2 + bbox_b = draw.textbbox((20, 20), word) # Check (w,h) of box a is (h,w) of box b assert box_size_a[0] == box_size_b[1] assert box_size_a[1] == box_size_b[0] + # Check bbox b is (20, 20, 20 + h, 20 + w) + assert bbox_b[0] == 20 + assert bbox_b[1] == 20 + assert bbox_b[2] == 20 + bbox_a[3] - bbox_a[1] + assert bbox_b[3] == 20 + bbox_a[2] - bbox_a[0] + + # text length is undefined for vertical text + pytest.raises(ValueError, draw.textlength, word) + def test_unrotated_transposed_font(self): img_grey = Image.new("L", (100, 100)) draw = ImageDraw.Draw(img_grey) @@ -310,15 +353,31 @@ def test_unrotated_transposed_font(self): # Original font draw.font = font - box_size_a = draw.textsize(word) + with pytest.warns(DeprecationWarning) as log: + box_size_a = draw.textsize(word) + assert len(log) == 1 + bbox_a = draw.textbbox((10, 10), word) + length_a = draw.textlength(word) # Rotated font draw.font = transposed_font - box_size_b = draw.textsize(word) + with pytest.warns(DeprecationWarning) as log: + box_size_b = draw.textsize(word) + assert len(log) == 1 + bbox_b = draw.textbbox((20, 20), word) + length_b = draw.textlength(word) # Check boxes a and b are same size assert box_size_a == box_size_b + # Check bbox b is (20, 20, 20 + w, 20 + h) + assert bbox_b[0] == 20 + assert bbox_b[1] == 20 + assert bbox_b[2] == 20 + bbox_a[2] - bbox_a[0] + assert bbox_b[3] == 20 + bbox_a[3] - bbox_a[1] + + assert length_a == length_b + def test_rotated_transposed_font_get_mask(self): # Arrange text = "mask this" @@ -373,9 +432,11 @@ def test_free_type_font_get_offset(self): text = "offset this" # Act - offset = font.getoffset(text) + with pytest.warns(DeprecationWarning) as log: + offset = font.getoffset(text) # Assert + assert len(log) == 1 assert offset == (0, 3) def test_free_type_font_get_mask(self): @@ -417,11 +478,11 @@ def test_default_font(self): # Assert assert_image_equal_tofile(im, "Tests/images/default_font.png") - def test_getsize_empty(self): + def test_getbbox_empty(self): # issue #2614 font = self.get_font() # should not crash. - assert (0, 0) == font.getsize("") + assert (0, 0, 0, 0) == font.getbbox("") def test_render_empty(self): # issue 2666 @@ -438,7 +499,7 @@ def test_unicode_pilfont(self): # issue #2826 font = ImageFont.load_default() with pytest.raises(UnicodeEncodeError): - font.getsize("’") + font.getbbox("’") def test_unicode_extended(self): # issue #3777 @@ -563,17 +624,29 @@ def test_imagefont_getters(self): assert t.font.x_ppem == 20 assert t.font.y_ppem == 20 assert t.font.glyphs == 4177 - assert t.getsize("A") == (12, 16) - assert t.getsize("AB") == (24, 16) - assert t.getsize("M") == (12, 16) - assert t.getsize("y") == (12, 20) - assert t.getsize("a") == (12, 16) - assert t.getsize_multiline("A") == (12, 16) - assert t.getsize_multiline("AB") == (24, 16) - assert t.getsize_multiline("a") == (12, 16) - assert t.getsize_multiline("ABC\n") == (36, 36) - assert t.getsize_multiline("ABC\nA") == (36, 36) - assert t.getsize_multiline("ABC\nAaaa") == (48, 36) + assert t.getbbox("A") == (0, 4, 12, 16) + assert t.getbbox("AB") == (0, 4, 24, 16) + assert t.getbbox("M") == (0, 4, 12, 16) + assert t.getbbox("y") == (0, 7, 12, 20) + assert t.getbbox("a") == (0, 7, 12, 16) + assert t.getlength("A") == 12 + assert t.getlength("AB") == 24 + assert t.getlength("M") == 12 + assert t.getlength("y") == 12 + assert t.getlength("a") == 12 + with pytest.warns(DeprecationWarning) as log: + assert t.getsize("A") == (12, 16) + assert t.getsize("AB") == (24, 16) + assert t.getsize("M") == (12, 16) + assert t.getsize("y") == (12, 20) + assert t.getsize("a") == (12, 16) + assert t.getsize_multiline("A") == (12, 16) + assert t.getsize_multiline("AB") == (24, 16) + assert t.getsize_multiline("a") == (12, 16) + assert t.getsize_multiline("ABC\n") == (36, 36) + assert t.getsize_multiline("ABC\nA") == (36, 36) + assert t.getsize_multiline("ABC\nAaaa") == (48, 36) + assert len(log) == 11 def test_getsize_stroke(self): # Arrange @@ -581,14 +654,22 @@ def test_getsize_stroke(self): # Act / Assert for stroke_width in [0, 2]: - assert t.getsize("A", stroke_width=stroke_width) == ( - 12 + stroke_width * 2, - 16 + stroke_width * 2, - ) - assert t.getsize_multiline("ABC\nAaaa", stroke_width=stroke_width) == ( - 48 + stroke_width * 2, - 36 + stroke_width * 4, + assert t.getbbox("A", stroke_width=stroke_width) == ( + 0 - stroke_width, + 4 - stroke_width, + 12 + stroke_width, + 16 + stroke_width, ) + with pytest.warns(DeprecationWarning) as log: + assert t.getsize("A", stroke_width=stroke_width) == ( + 12 + stroke_width * 2, + 16 + stroke_width * 2, + ) + assert t.getsize_multiline("ABC\nAaaa", stroke_width=stroke_width) == ( + 48 + stroke_width * 2, + 36 + stroke_width * 4, + ) + assert len(log) == 2 def test_complex_font_settings(self): # Arrange @@ -720,8 +801,11 @@ def test_textbbox_non_freetypefont(self): im = Image.new("RGB", (200, 200)) d = ImageDraw.Draw(im) default_font = ImageFont.load_default() - with pytest.raises(ValueError): - d.textbbox((0, 0), "test", font=default_font) + with pytest.warns(DeprecationWarning) as log: + width, height = d.textsize("test", font=default_font) + assert len(log) == 1 + assert d.textlength("test", font=default_font) == width + assert d.textbbox((0, 0), "test", font=default_font) == (0, 0, width, height) @pytest.mark.parametrize( "anchor, left, top", @@ -868,7 +952,7 @@ def test_bitmap_font_stroke(self): def test_standard_embedded_color(self): txt = "Hello World!" ttf = ImageFont.truetype(FONT_PATH, 40, layout_engine=self.LAYOUT_ENGINE) - ttf.getsize(txt) + ttf.getbbox(txt) im = Image.new("RGB", (300, 64), "white") d = ImageDraw.Draw(im) diff --git a/Tests/test_imagefontctl.py b/Tests/test_imagefontctl.py --- a/Tests/test_imagefontctl.py +++ b/Tests/test_imagefontctl.py @@ -140,8 +140,8 @@ def test_ligature_features(): target = "Tests/images/test_ligature_features.png" assert_image_similar_tofile(im, target, 0.5) - liga_size = ttf.getsize("fi", features=["-liga"]) - assert liga_size == (13, 19) + liga_bbox = ttf.getbbox("fi", features=["-liga"]) + assert liga_bbox == (0, 4, 13, 19) def test_kerning_features():
getsize_multiline doesn't take into account characters that extend below the baseline ### What did you do? I'm using `getsize_multiline` to compute the size of a text label that I render to an image. The image is exactly the size of the text label. I noticed that my text labels where cropped; specifically, when there are letters like `p` or `g` (which extend below the baseline) on the last line of text, these letters get cropped. The problem doesn't affect `getsize`, and can easily be exhibited by comparing the sizes reported by `getsize` vs `getsize_multiline` for a single line string like `g`. Example: ```python from PIL import ImageFont font = ImageFont.truetype("DroidSans", 20) print(font.getsize("g")) print(font.getsize_multiline("g")) ``` ### What did you expect to happen? The `getsize` and `getsize_multiline` methods should return the same size. ### What actually happened? With `DroidSans` in size 20: - `getsize` returns (10,24) - `getsize_multiline` returns (10,19) The `g` actually extends below if I create a label of size 10,19 and draw the string `g` on it, the `g` gets cropped. ### What are your OS, Python and Pillow versions? * OS: Arch Linux * Python: 3.9 * Pillow: 8.4.0 ```python #!/usr/bin/env python from PIL import Image, ImageFont, ImageDraw font = ImageFont.truetype("DroidSans", 20) text = "gÂp" size = font.getsize(text) image = Image.new("RGB", size) draw = ImageDraw.Draw(image) draw.text((0, 0), text, font=font) image.save("getsize.png") size = font.getsize_multiline(text) image = Image.new("RGB", size) draw = ImageDraw.Draw(image) draw.text((0, 0), text, font=font) image.save("getsize_multiline.png") ``` getsize: ![getsize](https://user-images.githubusercontent.com/171481/140619714-defdcb34-edfb-46a9-8618-00fc3d3ac358.png) getsize_multiline: ![getsize_multiline](https://user-images.githubusercontent.com/171481/140619717-1fdc4e28-f989-480d-844d-906b05376932.png) I imagine that the logic in getsize_multiline doesn't take into accounts characters that extend below the baseline. For now I'm going to just add a bit of padding on the last line 😅 but I guess there has to be a better way.
Of course, _immediately_ after opening that issue, I find a very promising method: `getmetrics()`, that precisely returns the ascent and the descend of a font. It looks like all I need to do is add the "descent" at the bottom of the label. I'll check that and if it works, I'll see if I can propose a patch for `getsize_multiline` and associated tests. Both `getsize` or `getsize_multilne` are often inaccurate (especially with italics or accents), but unfortunately they might never get fixed due to backwards compatibility (also, the definition of size can change depending on your use case, so the expected return value is unclear). I would not recommend using them in new code. The [docs for `getsize`](https://pillow.readthedocs.io/en/stable/_modules/PIL/ImageFont.html#FreeTypeFont.getsize_multiline) have this warning: > For historical reasons this function measures text height from the ascender line instead of the top, see Text anchors. If you wish to measure text height from the top, it is recommended to use the bottom value of getbbox() with anchor='lt' instead. It seems I didn't add a warning to the multiline version, likely because I didn't add a `getbbox_multiline` function (it would be an exact copy-paste). However, in most cases you will be using a font to draw onto an image using `ImageDraw.text`, which provides the two equivalent functions `textsize` and `multiline_textsize`. The [docs for `multiline_textsize`](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.ImageDraw.multiline_textsize) do have a similar warning: > For historical reasons this function measures text height as the distance between the top ascender line and bottom descender line, not the top and bottom of the text, see Text anchors. If you wish to measure text height from the top to the bottom of text, it is recommended to use multiline_textbbox() instead. In fact, I think this might not be entirely accurate due to the way Pillow computes line spacing - glancing at the source I suspect it is measuring to the bottom baseline instead in most cases and ignoring the last descender line like you mentioned. Instead, I believe [`ImageDraw.multiline_textbbox`](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.ImageDraw.multiline_textbbox) is the function you are looking for. It's documentation also provides a brief explanation: > The bounding box includes extra margins for some fonts, e.g. italics or accents. As for why `getsize` and `getsize_multiline` are not deprecated, IIRC I didn't propose this because the new functions work only with TrueType fonts, while the old functions work correctly with old "PIL" fonts. However, it might make sense to deprecate the old functions for TrueType fonts only. Edit: For more information see #4959 and the linked issues. > As for why `getsize` and `getsize_multiline` are not deprecated, IIRC I didn't propose this because the new functions work only with TrueType fonts, while the old functions work correctly with old "PIL" fonts. However, it might make sense to deprecate the old functions for TrueType fonts only. This deprecation sounds reasonable. What do others think? If adding warnings now (Pillow 9.0.0, 2022-01-02), it would be eligible for removal in Pillow 10.0.0 (2023-07-01), giving a nice long deprecation period. > Instead, I believe [`ImageDraw.multiline_textbbox`](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.ImageDraw.multiline_textbbox) is the function you are looking for. Yes indeed, thank you so much! I have one follow-up question: `ImageDraw.multiline_textbbox` requires an `ImageDraw` instance, but my program creates the image _after_ computing the text size (since the image holds the text label and nothing else). I did a little experiment and it looks like I can create an image of size (0,0) and use that to call `multiline_textbbox`, then create my final image with the proper size. Is that the right thing to do? Or might that break in the future? Thank you so much! I don't think that what you're describing should break in the future - and yes, it sounds like a reasonable way of doing things. > As for why `getsize` and `getsize_multiline` are not deprecated, IIRC I didn't propose this because the new functions work only with TrueType fonts, while the old functions work correctly with old "PIL" fonts. However, it might make sense to deprecate the old functions for TrueType fonts only. If we deprecate those, we should also then add `getbbox_multliline` and `TransposedFont.getbbox`, yes? > If we deprecate those, we should also then add getbbox_multliline and TransposedFont.getbbox, yes? Probably. That is what I was unsure about and why I didn't propose deprecating earlier. I'll take a look at this as part of https://github.com/python-pillow/Pillow/pull/6195#discussion_r847410876.
2022-06-20T04:29:21Z
9.1
python-pillow/Pillow
6,265
python-pillow__Pillow-6265
[ "6259" ]
9d988dab6aeb4346960a24b2ec423d8f16f8cddc
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -561,7 +561,7 @@ def _write_single_frame(im, fp, palette): def _write_multiple_frames(im, fp, palette): - duration = im.encoderinfo.get("duration", im.info.get("duration")) + duration = im.encoderinfo.get("duration") disposal = im.encoderinfo.get("disposal", im.info.get("disposal")) im_frames = [] @@ -579,6 +579,8 @@ def _write_multiple_frames(im, fp, palette): encoderinfo = im.encoderinfo.copy() if isinstance(duration, (list, tuple)): encoderinfo["duration"] = duration[frame_count] + elif duration is None and "duration" in im_frame.info: + encoderinfo["duration"] = im_frame.info["duration"] if isinstance(disposal, (list, tuple)): encoderinfo["disposal"] = disposal[frame_count] frame_count += 1
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -3,7 +3,7 @@ import pytest -from PIL import GifImagePlugin, Image, ImageDraw, ImagePalette, features +from PIL import GifImagePlugin, Image, ImageDraw, ImagePalette, ImageSequence, features from .helper import ( assert_image_equal, @@ -691,6 +691,23 @@ def test_multiple_duration(tmp_path): pass +def test_roundtrip_info_duration(tmp_path): + duration_list = [100, 500, 500] + + out = str(tmp_path / "temp.gif") + with Image.open("Tests/images/transparent_dispose.gif") as im: + assert [ + frame.info["duration"] for frame in ImageSequence.Iterator(im) + ] == duration_list + + im.save(out, save_all=True) + + with Image.open(out) as reloaded: + assert [ + frame.info["duration"] for frame in ImageSequence.Iterator(reloaded) + ] == duration_list + + def test_identical_frames(tmp_path): duration_list = [1000, 1500, 2000, 4000]
GIF durations should be preserved from frame info <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? Copied an animated GIF: ```python with Image.open('Tazspin.gif') as im: im.save(f'new.gif', save_all=True, optimize=True, interlace=0) ``` ### What did you expect to happen? Hoped the copy would be something like the original Tazspin.gif: ![Tazspin](https://user-images.githubusercontent.com/24783736/166316458-3e8e3bfc-c5ac-4e88-86b2-7dd23c2e7371.gif) ### What actually happened? Got this: ![new](https://user-images.githubusercontent.com/24783736/166316569-938b85af-8bd5-4bc4-b092-627a1d5b1bae.gif) ### What are your OS, Python and Pillow versions? * OS: Windows 10 * Python: 3.10.4 * Pillow: 9.1.0 (slightly modified but you'll get a very similar result with stock 9.1.0) #### Discussion: Duration has been a problem in the past. I think that in the absence of a `duration=` arg to `.save()`, the durations ("delay time" in the GIF spec) from the individual frames should be preserved in the output. Maybe something like this: in `_write_multiple_frames()` (in `GifImagePlugin.py`), delete the line ```python duration = im.encoderinfo.get("duration", im.info.get("duration")) ``` Then modify the code that sets `im.encoderinfo` from `im_frame.info`: ```python for k, v in im_frame.info.items(): if k == "transparency" or k == "duration": continue im.encoderinfo.setdefault(k, v) ``` (Note I am including code changed in PR #6176. I am not making a PR out of this because I don't know how to deal with such conflicts and because I am not sure if this is a good fix. Need input from @radarhere.) And then before the line `if isinstance(duration...`, insert: ```python if "duration" in im_frame.info: encoderinfo.setdefault("duration", im_frame.info["duration"]) duration = encoderinfo.get("duration") ``` This seems to give me the desired result: ![new_910_fix_d1](https://user-images.githubusercontent.com/24783736/166322842-d604bcd2-0171-41a9-baa2-0d635298ad06.gif) I hope it doesn't break anything. <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. -->
2022-05-03T10:15:17Z
9.1
python-pillow/Pillow
6,234
python-pillow__Pillow-6234
[ "6209" ]
de1ba373e10065e7bffe4bdb18a4aec40ef306a2
diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -711,8 +711,13 @@ def font_variant( :return: A FreeTypeFont object. """ + if font is None: + try: + font = BytesIO(self.font_bytes) + except AttributeError: + font = self.path return FreeTypeFont( - font=self.path if font is None else font, + font=font, size=self.size if size is None else size, index=self.index if index is None else index, encoding=self.encoding if encoding is None else encoding,
diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -65,9 +65,12 @@ def _font_as_bytes(self): return font_bytes def test_font_with_filelike(self): - ImageFont.truetype( + ttf = ImageFont.truetype( self._font_as_bytes(), FONT_SIZE, layout_engine=self.LAYOUT_ENGINE ) + ttf_copy = ttf.font_variant() + assert ttf_copy.font_bytes == ttf.font_bytes + self._render(self._font_as_bytes()) # Usage note: making two fonts from the same buffer fails. # shared_bytes = self._font_as_bytes()
Using font_variant on a font whose path is defined by BytesIO fails ### What did you do? Opened a font using ```py font = ImageFont.truetype( BytesIO(pkgutil.get_data(__package__, path)), size ) ``` then tried to edit the font using font_variant. ```py # doesn't work, it raises "OSError: cannot open resource" font = font.font_variant(size=font.size+10) ``` However, by doing a bit more code i managed to get it to work ```py # does work font = font.font_variant( font=BytesIO(font.path.getvalue()), size=font.size+10 ) ``` Aditionally ```py # does work font.path.seek(0) font = font.font_variant( size=font.size+10 ) ``` I assume this is something todo with font_variant parsing in `font.path` to the init of a new font object and as `BytesIO` is already read, it can't be read again. To fix this it could have a check if its a file like object and seek to the begining again? ### What did you expect to happen? I expected the font to be successfully changed ### What actually happened? It raised the error ```py line 101, in get_font_size font = font.font_variant(size=font.size+10) line 715, in font_variant return FreeTypeFont( line 230, in __init__ load_from_bytes(font) line 211, in load_from_bytes self.font = core.getfont( OSError: cannot open resource ``` ### What are your OS, Python and Pillow versions? * OS: Windows 11 * Python: 3.10 * Pillow: 9.1.0
https://pillow.readthedocs.io/en/stable/reference/ImageFont.html#PIL.ImageFont.truetype > Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given size. While I'm not able to replicate your problem (when I try, I receive an error at `ImageFont.truetype()` as well, not just at `font_variant()`), Pillow would be seeing your `BytesIO` object and thinking that you are passing in the contents of the font file, not the path. @14ROVI did that answer your question? What I'm trying to say is that the situation you describe shouldn't work at all, not just fail for variants. This is not the intended use. If you would like us to investigate why it's working for you at all, please let us know what font you are using. @radarhere Thank you for investigating. BytesIO is a file like object which supports the reading and writing needed for loading the font hence loading the font initally works. However, when trying to use `ImageFont.font_variant()` on that font it fails. This is because the font "file" has already been read. It's not really a massive issue as it can be fixed by using `file.seek(0)` before using `font_variant` but it was annoying as it would make sense to not have to bother with that to change the size of the font. ![image](https://user-images.githubusercontent.com/29734170/164485901-d58e5ea0-8f1d-4096-b00c-ea1e9b6f993c.png) With this example you may ask *why do it this way* to which i respond not in this example but if you have to load resources off of the internet or some other method where you dont have a file path, it would be nicer to not have to bother. I hope this explains it better. please let me know if ive missed the point of `font_variant` however.
2022-04-21T21:41:19Z
9.1
python-pillow/Pillow
6,242
python-pillow__Pillow-6242
[ "6240" ]
7d5162cb371a7199a9a141a70789aa95d41daeb5
diff --git a/src/PIL/PpmImagePlugin.py b/src/PIL/PpmImagePlugin.py --- a/src/PIL/PpmImagePlugin.py +++ b/src/PIL/PpmImagePlugin.py @@ -116,6 +116,10 @@ def _open(self): break elif ix == 2: # token is maxval maxval = token + if not 0 < maxval < 65536: + raise ValueError( + "maxval must be greater than 0 and less than 65536" + ) if maxval > 255 and mode == "L": self.mode = "I"
diff --git a/Tests/test_file_ppm.py b/Tests/test_file_ppm.py --- a/Tests/test_file_ppm.py +++ b/Tests/test_file_ppm.py @@ -145,6 +145,19 @@ def test_truncated_file(tmp_path): im.load() +@pytest.mark.parametrize("maxval", (0, 65536)) +def test_invalid_maxval(maxval, tmp_path): + path = str(tmp_path / "temp.ppm") + with open(path, "w") as f: + f.write("P6\n3 1 " + str(maxval)) + + with pytest.raises(ValueError) as e: + with Image.open(path): + pass + + assert str(e.value) == "maxval must be greater than 0 and less than 65536" + + def test_neg_ppm(): # Storage.c accepted negative values for xsize, ysize. the # internal open_ppm function didn't check for sanity but it
ZeroDivisionError is raised when the `maxval` of the PPM metadata is 0 <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> Hi, Thank you for developing and maintaining this project. Recently I am fuzzing this library for fun, and I found the test case which raises ZeroDivisionError. ### What did you do? ```python3 from PIL import Image import io # Load hopper.ppm. Assumes the current directory is the root of this repository. with open('Tests/images/hopper.ppm', 'rb') as f: data = bytearray(f.read()) # Sets the maximum value 0 data[49] = 0x30 data[50] = 0x30 data[51] = 0x30 # Raises ZeroDivisionError with Image.open(io.BytesIO(data)) as img: img.load() ``` ### What did you expect to happen? The file is broken, so some error should be raised. But `ZeroDivisionError` may be a little confusing. ### What actually happened? ``` Traceback (most recent call last): File "issue1.py", line 15, in <module> img.load() File "/usr/local/lib/python3.8/site-packages/PIL/ImageFile.py", line 234, in load err_code = decoder.decode(b"")[1] File "/usr/local/lib/python3.8/site-packages/PIL/PpmImagePlugin.py", line 152, in decode value = min(out_max, round(value / maxval * out_max)) ZeroDivisionError: division by zero ``` ### What are your OS, Python and Pillow versions? * OS: Debian GNU/Linux 11 (bullseye) * Python: 3.8.13 * Pillow: 9.1.0 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> I am happy to create the pull request to fix this issue, but I am not very sure which exception should be raised here.
http://netpbm.sourceforge.net/doc/ppm.html states that maxval "Must be less than 65536 and more than zero", so yes, I agree it is broken. I've created #6242 to raise a "Invalid maxval" ValueError. Thank you. LGTM!
2022-04-25T00:19:54Z
9.1
python-pillow/Pillow
6,188
python-pillow__Pillow-6188
[ "6187" ]
4996f84fb3fb80dc1d4e8288ff45ef11f8b162cc
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1720,6 +1720,8 @@ def point(self, data): # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode") + if mode != "F": + lut = [round(i) for i in lut] return self._new(self.im.point(lut, mode)) def putalpha(self, alpha):
diff --git a/Tests/test_image_point.py b/Tests/test_image_point.py --- a/Tests/test_image_point.py +++ b/Tests/test_image_point.py @@ -10,6 +10,7 @@ def test_sanity(): im.point(list(range(256))) im.point(list(range(256)) * 3) im.point(lambda x: x) + im.point(lambda x: x * 1.2) im = im.convert("I") with pytest.raises(ValueError):
'float' object cannot be interpreted as an integer exception when applying point transforms ### What did you do? Following the docs to apply point transforms: https://pillow.readthedocs.io/en/stable/handbook/tutorial.html?highlight=.point(#applying-point-transforms ### What actually happened? The following exception was raised: `'float' object cannot be interpreted as an integer`. ### What are your OS, Python and Pillow versions? * OS: Windows 11 Pro (22000.556) * Python: 3.10.4 (packaged by conda-forge) * Pillow: 9.1.0 Code to reproduce ```python from PIL import Image image = Image.open(image_path).convert('RGBA') alpha_channel = image.getchannel('A') image.putalpha(alpha_channel.point(lambda x: x * 0.5)) ``` With Pillow 8.3.2 and Python 3.8, the above code worked well. Edit: I've tested Pillow 9.1.0 with Python 3.9.12 and it works fine, so it seems to be an issue related to Python 3.10.x
Thanks. This would be because of https://docs.python.org/3/c-api/long.html#c.PyLong_AsLong > Changed in version 3.10: This function will no longer use `__int__()`. I've created PR #6188 to resolve this.
2022-04-06T22:55:39Z
9.1
python-pillow/Pillow
6,128
python-pillow__Pillow-6128
[ "6115" ]
475b7233d6c6341f750829dbdd5123002bed57b7
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -424,7 +424,7 @@ def _close__fp(self): RAWMODE = {"1": "L", "L": "L", "P": "P"} -def _normalize_mode(im, initial_call=False): +def _normalize_mode(im): """ Takes an image (or frame), returns an image in a mode that is appropriate for saving in a Gif. @@ -432,31 +432,20 @@ def _normalize_mode(im, initial_call=False): It may return the original image, or it may return an image converted to palette or 'L' mode. - UNDONE: What is the point of mucking with the initial call palette, for - an image that shouldn't have a palette, or it would be a mode 'P' and - get returned in the RAWMODE clause. - :param im: Image object - :param initial_call: Default false, set to true for a single frame. :returns: Image object """ if im.mode in RAWMODE: im.load() return im if Image.getmodebase(im.mode) == "RGB": - if initial_call: - palette_size = 256 - if im.palette: - palette_size = len(im.palette.getdata()[1]) // 3 - im = im.convert("P", palette=Image.Palette.ADAPTIVE, colors=palette_size) - if im.palette.mode == "RGBA": - for rgba in im.palette.colors.keys(): - if rgba[3] == 0: - im.info["transparency"] = im.palette.colors[rgba] - break - return im - else: - return im.convert("P") + im = im.convert("P", palette=Image.Palette.ADAPTIVE) + if im.palette.mode == "RGBA": + for rgba in im.palette.colors.keys(): + if rgba[3] == 0: + im.info["transparency"] = im.palette.colors[rgba] + break + return im return im.convert("L") @@ -514,7 +503,7 @@ def _normalize_palette(im, palette, info): def _write_single_frame(im, fp, palette): - im_out = _normalize_mode(im, True) + im_out = _normalize_mode(im) for k, v in im_out.info.items(): im.encoderinfo.setdefault(k, v) im_out = _normalize_palette(im_out, palette, im.encoderinfo) @@ -646,11 +635,14 @@ def get_interlace(im): def _write_local_header(fp, im, offset, flags): transparent_color_exists = False try: - transparency = im.encoderinfo["transparency"] - except KeyError: + if "transparency" in im.encoderinfo: + transparency = im.encoderinfo["transparency"] + else: + transparency = im.info["transparency"] + transparency = int(transparency) + except (KeyError, ValueError): pass else: - transparency = int(transparency) # optimize the block away if transparent color is not used transparent_color_exists = True
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -842,6 +842,17 @@ def test_rgb_transparency(tmp_path): assert "transparency" not in reloaded.info +def test_rgba_transparency(tmp_path): + out = str(tmp_path / "temp.gif") + + im = hopper("P") + im.save(out, save_all=True, append_images=[Image.new("RGBA", im.size)]) + + with Image.open(out) as reloaded: + reloaded.seek(1) + assert_image_equal(hopper("P").convert("RGB"), reloaded) + + def test_bbox(tmp_path): out = str(tmp_path / "temp.gif")
Broken background on transparent GIFs built from individual frames The background of transparent GIFs constructed from Images seems to not quite see the transparent color correctly. ```py from PIL import Image with Image.open('test.gif') as im: images = [] durations = [] for i in range(im.n_frames): im.seek(i) im.convert('RGBA') im_temp = Image.new('RGBA',im.size,(0,0,0,0)) im_temp.paste(im,(0,0)) images.append(im_temp) durations.append(im.info['duration']) images[0].save( 'test-out.gif', interlace=True, save_all=True, append_images=images[1:], loop=0, duration=durations, disposal=2, transparency = 255, background = 255, optimize=False ) ``` This should copy the image perfectly, but there are artifacts. ![Input](https://user-images.githubusercontent.com/59123926/157148158-e21b8ba6-bcfa-4c50-bcbc-3ddc41ed1b48.gif) ![Output](https://user-images.githubusercontent.com/59123926/157148265-a302bff2-5be0-40e0-9f4c-dbe8f97b12c4.gif) [Here's the venv I used to test this, in a zip.](https://github.com/python-pillow/Pillow/files/8201983/pillowtest.zip)
I suspect that setting transparency and background to 255 is the issue. These values are indexes into the color palette but your palette only has 13 entries, not 255. I fed the test input and output .gifs provided by @balt-is-you-and-shift into a small script I wrote, and here is the output: ``` % python3 mk_ani.py -i test.gif PIL 9.0.1 "test.gif" size=(32, 32) mode=P is_ani=True #frames=8 loop=0 palette_size=13 0: disposal=2 transparency=0 duration=1000 background='idx=0 color=(0, 0, 0) #000000' 1: disposal=2 transparency=None duration=50 background='idx=0 color=(0, 0, 0) #000000' 2: disposal=2 transparency=None duration=70 background='idx=0 color=(0, 0, 0) #000000' 3: disposal=2 transparency=None duration=200 background='idx=0 color=(0, 0, 0) #000000' 4: disposal=2 transparency=None duration=100 background='idx=0 color=(0, 0, 0) #000000' 5: disposal=2 transparency=None duration=100 background='idx=0 color=(0, 0, 0) #000000' 6: disposal=2 transparency=None duration=100 background='idx=0 color=(0, 0, 0) #000000' 7: disposal=2 transparency=None duration=50 background='idx=0 color=(0, 0, 0) #000000' % python3 mk_ani.py -i test-out.gif PIL 9.0.1 "test-out.gif" size=(32, 32) mode=P is_ani=True #frames=8 loop=0 palette_size=13 0: disposal=2 transparency=255 duration=1000 background='idx=255 color=None None' 1: disposal=2 transparency=None duration=50 background='idx=255 color=None None' 2: disposal=2 transparency=None duration=70 background='idx=255 color=None None' 3: disposal=2 transparency=None duration=200 background='idx=255 color=None None' 4: disposal=2 transparency=None duration=100 background='idx=255 color=None None' 5: disposal=2 transparency=None duration=100 background='idx=255 color=None None' 6: disposal=2 transparency=None duration=100 background='idx=255 color=None None' 7: disposal=2 transparency=None duration=50 background='idx=255 color=None None' ``` When I copied the background and transparency from the source to the save() call, I think I got the results you desire: ``` % python3 mk_ani.py -i test-out-t0-bg-none.gif PIL 9.0.1 "test-out-t0-bg-none.gif" size=(32, 32) mode=P is_ani=True #frames=8 loop=0 palette_size=13 0: disposal=2 transparency=0 duration=1000 background='idx=0 color=(0, 0, 0) #000000' 1: disposal=2 transparency=None duration=50 background='idx=0 color=(0, 0, 0) #000000' 2: disposal=2 transparency=None duration=70 background='idx=0 color=(0, 0, 0) #000000' 3: disposal=2 transparency=None duration=200 background='idx=0 color=(0, 0, 0) #000000' 4: disposal=2 transparency=None duration=100 background='idx=0 color=(0, 0, 0) #000000' 5: disposal=2 transparency=None duration=100 background='idx=0 color=(0, 0, 0) #000000' 6: disposal=2 transparency=None duration=100 background='idx=0 color=(0, 0, 0) #000000' 7: disposal=2 transparency=None duration=50 background='idx=0 color=(0, 0, 0) #000000' ``` ![test-out-t0-bg-none](https://user-images.githubusercontent.com/33208090/157178443-0713496d-d0fb-4f54-98ad-a39ee2c85a42.gif) Take a look at this. If I set the transparency using the key from the info dictionary, it works. ```python from PIL import Image with Image.open('test.gif') as im: images = [] durations = [] transparency = im.info["transparency"] for i in range(im.n_frames): im.seek(i) im.convert('RGBA') im_temp = Image.new('RGBA',im.size,(0,0,0,0)) im_temp.paste(im,(0,0)) images.append(im_temp) durations.append(im.info['duration']) images[0].save( 'test-out.gif', interlace=True, save_all=True, append_images=images[1:], loop=0, duration=durations, disposal=2, transparency = transparency, background = 255, optimize=False ) ``` ![test-out](https://user-images.githubusercontent.com/3112309/157183652-50170ee9-bf1b-4e83-a484-b646d38ca402.gif) This wouldn't solve the issue well, bad example. I'll make a better example of the issue when I can. [test-v2.zip](https://github.com/python-pillow/Pillow/files/8207292/test-v2.zip) Not very copy-pastable, but it's a much better example of the problem at hand. _Sorry for the multiple edits, I'm trying to get an example that best shows the issue._ ```py from PIL import Image import json with open('durations.json','rb') as f: durations = json.load(f) images = [] for n in range(8): with Image.open(f'test{n}.png') as im: im = im.convert('RGBA').resize([n*8 for n in im.size],Image.NEAREST) images.append(im) images[0].save( #GIFs have this issue 'test.gif', interlace=True, save_all=True, append_images=images[1:], loop=0, duration=durations, disposal=2, transparency = 255, background = 255, optimize=False ) images[0].save( #APNGs don't have this issue, showing it's an issue with GIF saving 'test.png', format='PNG', save_all=True, append_images=images, default_image=True, loop=0, durations=durations ) ``` ![test](https://user-images.githubusercontent.com/59123926/157268862-d96545ce-bc57-44e2-bea9-497f03d9f704.png) APNG ![test](https://user-images.githubusercontent.com/59123926/157268863-ea294ebd-c9f0-4b7b-820f-89a827e4c91e.gif) GIF @resnbl @radarhere Not sure why you are setting transparency=255 (or why PIL is not complaining about it!). According to the docs (https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html#saving), transparency is an "index", i.e. offset into the color palette indicating which "color" should denote transparent pixels. Your image palette does not contain 256 colors (only 13 are used), so you are not getting the proper results. For the test provided, using transparency=0 works. The same applies to the background setting: it is an index into the color palette. Again, setting to 0 will get what you want for this. (@radarhere : your solution is missing this part as well.) FYI: here is the color palette for your generated GIF: ``` Global palette: 0 #000000 (0, 0, 0) 1 #00E436 (0, 228, 54) 2 #FFEC27 (255, 236, 39) 3 #FF004D (255, 0, 77) 4 #29ADFF (41, 173, 255) 5 #00B543 (0, 181, 67) 6 #FF6C24 (255, 108, 36) 7 #BE1250 (190, 18, 80) 8 #065AB5 (6, 90, 181) 9 #A8E72E (168, 231, 46) 10 #C2C3C7 (194, 195, 199) 11 #F3EF7D (243, 239, 125) 12 #FF6E59 (255, 110, 89) ``` If there is anything amiss with PIL, I think it is that the `.save()` method did not complain about the transparency and background arguments being outside the range of the generated palette table. On a side note: I went through the same thing as you: generating an animated image from a list of images. In my solution, I chose a file naming convention over a .json durations file. I named my inputs "nn-dDDD-blah.png" where "nn" is the image order index (for easily sorting the output of a glob.glob('*.png') call), "DDD" is the duration in msecs., and "blah" is anything but was used for the default output filename "blah.{gif|png}". Just another way of doing things... ![test](https://user-images.githubusercontent.com/33208090/157293804-c9851207-87d4-4c3f-be20-6aa80fcbd021.gif) See, the problem with that is that _setting transparency and background to 255 worked fine in previous versions, and setting them both to 0 won't work if the majority of the image isn't transparent._
2022-03-12T04:19:19Z
9
python-pillow/Pillow
6,124
python-pillow__Pillow-6124
[ "6123" ]
515957b2ac2cd1b85a3008550a99820bf643e9e4
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -3478,12 +3478,12 @@ def load(self, data): self._loaded_exif = data self._data.clear() self._ifds.clear() + if data and data.startswith(b"Exif\x00\x00"): + data = data[6:] if not data: self._info = None return - if data.startswith(b"Exif\x00\x00"): - data = data[6:] self.fp = io.BytesIO(data) self.head = self.fp.read(8) # process dictionary
diff --git a/Tests/test_image.py b/Tests/test_image.py --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -666,6 +666,19 @@ def act(fp): assert not fp.closed + def test_empty_exif(self): + with Image.open("Tests/images/exif.png") as im: + exif = im.getexif() + assert dict(exif) != {} + + # Test that exif data is cleared after another load + exif.load(None) + assert dict(exif) == {} + + # Test loading just the EXIF header + exif.load(b"Exif\x00\x00") + assert dict(exif) == {} + @mark_if_feature_version( pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing" )
Support for a "blank" exif <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? load a image and its exif is b'Exif\x00\x00' ```python im=Image.open(/path/to/img) im._exif is None ``` ``` True ``` ```python im.info ``` ``` {'jfif': 257, 'jfif_version': (1, 1), 'dpi': (1, 1), 'jfif_unit': 1, 'jfif_density': (1, 1), 'exif': b'Exif\x00\x00'} ``` ```python im.getexif() ``` ``` Traceback (most recent call last): File "/home/me/anaconda3/envs/ppdetection213/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3444, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "/tmp/ipykernel_15028/2749469980.py", line 1, in <module> im.getexif() File "/home/me/anaconda3/envs/ppdetection213/lib/python3.9/site-packages/PIL/Image.py", line 1391, in getexif self._exif.load(exif_info) File "/home/me/anaconda3/envs/ppdetection213/lib/python3.9/site-packages/PIL/Image.py", line 3422, in load self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head) File "/home/me/anaconda3/envs/ppdetection213/lib/python3.9/site-packages/PIL/TiffImagePlugin.py", line 491, in __init__ raise SyntaxError(f"not a TIFF file (header {repr(ifh)} not valid)") File "<string>", line unknown SyntaxError: not a TIFF file (header b'' not valid) ``` ### What did you expect to happen? Nothing to be done. Since functions like ```ImageOps.exif_transpose``` calls ```im.getexif()```, so I will expect that no errors should be raised. ### What actually happened? the ```getexif()``` function will call Exif() to initiate a blank Exif instance, since the im._exif is None. And then the Exif() instance will load the im.info.get('exif'), which is ```b'Exif\x00\x00'```. In the load function, the ```b'Exif\x00\x00'``` will be dropped by this [line](https://github.com/python-pillow/Pillow/blob/29960c6610ba542b9ec137f2f459a497c6365083/src/PIL/Image.py#L3486). So a `b''` is passed to `TiffImagePlugin.ImageFileDirectory_v2(self.head)`. And since `b''` is not accepted by `TiffImagePlugin.ImageFileDirectory_v2`, an error will be raised. BTW, these three lines in Exif.load(): ```python if data == self._loaded_exif: return self._loaded_exif = data ``` make the code work when calling im.getexif() the second time. ### What are your OS, Python and Pillow versions? * OS: Linux * Python: 3.9.7 * Pillow: 8.4.0 and 9.0.1 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> ```python im=Image.open(/path/to/img) im.getexif() ``` ![testimage](https://user-images.githubusercontent.com/41351449/157874204-1f2e067b-46af-4d47-ab88-e57af6bb3849.jpeg) I wonder if this repo is considering returning a blank Exif in this case, instead of raising an error. I have no idea whether this would lead to other unknown damages or not.
2022-03-11T21:27:11Z
9
python-pillow/Pillow
6,101
python-pillow__Pillow-6101
[ "6100" ]
37d28ce5143d0eb7ca9cd59d24d623855072506a
diff --git a/src/PIL/MpoImagePlugin.py b/src/PIL/MpoImagePlugin.py --- a/src/PIL/MpoImagePlugin.py +++ b/src/PIL/MpoImagePlugin.py @@ -46,6 +46,7 @@ def _open(self): self._after_jpeg_open() def _after_jpeg_open(self, mpheader=None): + self._initial_size = self.size self.mpinfo = mpheader if mpheader is not None else self._getmp() self.n_frames = self.mpinfo[0xB001] self.__mpoffsets = [ @@ -77,6 +78,7 @@ def seek(self, frame): segment = self.fp.read(2) if not segment: raise ValueError("No data found for frame") + self._size = self._initial_size if i16(segment) == 0xFFE1: # APP1 n = i16(self.fp.read(2)) - 2 self.info["exif"] = ImageFile._safe_read(self.fp, n)
diff --git a/Tests/test_file_mpo.py b/Tests/test_file_mpo.py --- a/Tests/test_file_mpo.py +++ b/Tests/test_file_mpo.py @@ -85,6 +85,9 @@ def test_frame_size(): im.seek(1) assert im.size == (680, 480) + im.seek(0) + assert im.size == (640, 480) + def test_ignore_frame_size(): # Ignore the different size of the second frame
Cannot modify the first frame of a MPO with asymmetric sized frames after seek ### What did you do? Did a seek(1) to the second frame followed by a seek(0) back to the first, and a transpose ### What did you expect to happen? The transpose ### What actually happened? Segmentation fault: 11 ### What are your OS, Python and Pillow versions? * OS: OSX 10.15.7 and Ubuntu 20.04 * Python: 3.8.11 and 3.10.2 * Pillow: 9.0.1 This is an edge case issue with images created by the Nikon coolpix 500b (and possibly others), which appears to embed a couple "thumbnails" in the image files. Pillow (reasonably) detects this as a 3-frame MPO. For some reason, however, seeking back to the first frame and trying to modify it after seeking to any other frame crashes with a seg fault. For the example below I used this image (not sure on the licensing, just the first I googled): https://img.photographyblog.com/reviews/nikon_coolpix_b500/photos/nikon_coolpix_b500_02.jpg ```python from PIL import Image im = Image.open('nikon_coolpix_b500_02.jpg') im.seek(1) im.seek(0) im.transpose(Image.FLIP_LEFT_RIGHT) # => Segment fault: 11 ``` If it helps, I noticed that the `im.size` doesn't update after the `seek(0)` back to the first frame, even though `tell` reports the correct frame: ```python im = Image.open('nikon_coolpix_b500_02.jpg') im.size # => (4608, 3456) im.seek(1) im.size # => (640, 480) im.seek(0) im.size # => (640, 480) im.tell() # => 0 ``` For my particular case, the problematic usage was some legacy code trying to detect animations that is better handled by checking `n_frames`, so I was able to work around it. Mainly documenting the issue in case anyone else runs into it.
2022-03-01T08:16:25Z
9
python-pillow/Pillow
6,097
python-pillow__Pillow-6097
[ "4513" ]
37d28ce5143d0eb7ca9cd59d24d623855072506a
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -49,7 +49,7 @@ # PILLOW_VERSION was removed in Pillow 9.0.0. # Use __version__ instead. from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins -from ._binary import i32le +from ._binary import i32le, o32be, o32le from ._util import deferred_error, isPath @@ -1416,6 +1416,7 @@ def getexif(self): "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): + self._exif.bigtiff = self.tag_v2._bigtiff self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: @@ -3423,6 +3424,7 @@ def _apply_env_variables(env=None): class Exif(MutableMapping): endian = None + bigtiff = False def __init__(self): self._data = {} @@ -3458,10 +3460,15 @@ def _get_ifd_dict(self, offset): return self._fixup_dict(info) def _get_head(self): + version = b"\x2B" if self.bigtiff else b"\x2A" if self.endian == "<": - return b"II\x2A\x00\x08\x00\x00\x00" + head = b"II" + version + b"\x00" + o32le(8) else: - return b"MM\x00\x2A\x00\x00\x00\x08" + head = b"MM\x00" + version + o32be(8) + if self.bigtiff: + head += o32le(8) if self.endian == "<" else o32be(8) + head += b"\x00\x00\x00\x00" + return head def load(self, data): # Extract EXIF information. This is highly experimental, diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -260,6 +260,8 @@ b"II\x2A\x00", # Valid TIFF header with little-endian byte order b"MM\x2A\x00", # Invalid TIFF header, assume big-endian b"II\x00\x2A", # Invalid TIFF header, assume little-endian + b"MM\x00\x2B", # BigTIFF with big-endian byte order + b"II\x2B\x00", # BigTIFF with little-endian byte order ] @@ -502,11 +504,14 @@ def __init__(self, ifh=b"II\052\0\0\0\0\0", prefix=None, group=None): self._endian = "<" else: raise SyntaxError("not a TIFF IFD") + self._bigtiff = ifh[2] == 43 self.group = group self.tagtype = {} """ Dictionary of tag types """ self.reset() - (self.next,) = self._unpack("L", ifh[4:]) + (self.next,) = ( + self._unpack("Q", ifh[8:]) if self._bigtiff else self._unpack("L", ifh[4:]) + ) self._legacy_api = False prefix = property(lambda self: self._prefix) @@ -699,6 +704,7 @@ def _register_basic(idx_fmt_name): (TiffTags.FLOAT, "f", "float"), (TiffTags.DOUBLE, "d", "double"), (TiffTags.IFD, "L", "long"), + (TiffTags.LONG8, "Q", "long8"), ], ) ) @@ -776,8 +782,17 @@ def load(self, fp): self._offset = fp.tell() try: - for i in range(self._unpack("H", self._ensure_read(fp, 2))[0]): - tag, typ, count, data = self._unpack("HHL4s", self._ensure_read(fp, 12)) + tag_count = ( + self._unpack("Q", self._ensure_read(fp, 8)) + if self._bigtiff + else self._unpack("H", self._ensure_read(fp, 2)) + )[0] + for i in range(tag_count): + tag, typ, count, data = ( + self._unpack("HHQ8s", self._ensure_read(fp, 20)) + if self._bigtiff + else self._unpack("HHL4s", self._ensure_read(fp, 12)) + ) tagname = TiffTags.lookup(tag, self.group).name typname = TYPES.get(typ, "unknown") @@ -789,9 +804,9 @@ def load(self, fp): logger.debug(msg + f" - unsupported type {typ}") continue # ignore unsupported type size = count * unit_size - if size > 4: + if size > (8 if self._bigtiff else 4): here = fp.tell() - (offset,) = self._unpack("L", data) + (offset,) = self._unpack("Q" if self._bigtiff else "L", data) msg += f" Tag Location: {here} - Data Location: {offset}" fp.seek(offset) data = ImageFile._safe_read(fp, size) @@ -820,7 +835,11 @@ def load(self, fp): ) logger.debug(msg) - (self.next,) = self._unpack("L", self._ensure_read(fp, 4)) + (self.next,) = ( + self._unpack("Q", self._ensure_read(fp, 8)) + if self._bigtiff + else self._unpack("L", self._ensure_read(fp, 4)) + ) except OSError as msg: warnings.warn(str(msg)) return @@ -1042,6 +1061,8 @@ def _open(self): # Header ifh = self.fp.read(8) + if ifh[2] == 43: + ifh += self.fp.read(8) self.tag_v2 = ImageFileDirectory_v2(ifh) diff --git a/src/PIL/TiffTags.py b/src/PIL/TiffTags.py --- a/src/PIL/TiffTags.py +++ b/src/PIL/TiffTags.py @@ -74,6 +74,7 @@ def lookup(tag, group=None): FLOAT = 11 DOUBLE = 12 IFD = 13 +LONG8 = 16 TAGS_V2 = { 254: ("NewSubfileType", LONG, 1),
diff --git a/Tests/images/hopper_bigtiff.tif b/Tests/images/hopper_bigtiff.tif new file mode 100644 Binary files /dev/null and b/Tests/images/hopper_bigtiff.tif differ diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -87,6 +87,10 @@ def test_mac_tiff(self): assert_image_similar_tofile(im, "Tests/images/pil136.png", 1) + def test_bigtiff(self): + with Image.open("Tests/images/hopper_bigtiff.tif") as im: + assert_image_equal_tofile(im, "Tests/images/hopper.tif") + @pytest.mark.parametrize( "file_name,mode,size,offset", [
PIL cannot read BigTIFF <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? I'm trying to open an orthomosaic geotiff into Python to crop into 1000x1000 tiles. I am able to open some tif files in my notebook, but other files return an UnidentifiedImageError. I have set up my notebook using a Dockerfile that creates a conda environment. ### What did you expect to happen? I expected that my code would work the same on all of my tif files - they are all 4-band 8-bit. This code works with a tif file that is 992 MB, but it doesn't work with a file that's 691 MB. ### What actually happened? ``` --------------------------------------------------------------------------- UnidentifiedImageError Traceback (most recent call last) <ipython-input-85-c7f17ab4563e> in <module> 6 7 # break it up into crops ----> 8 for k, piece in enumerate(crop(infile, tile_height, tile_width, stride, img_dict, prj_name), start_num): 9 img=Image.new('RGB', (tile_height, tile_width), (255, 255, 255)) 10 print(img.size) <ipython-input-83-c9b468169840> in crop(infile, tile_height, tile_width, stride, img_dict, prj_name) 5 6 def crop(infile, tile_height, tile_width, stride, img_dict, prj_name): ----> 7 im = Image.open(infile) 8 img_width, img_height = im.size 9 print(im.size) /opt/conda/envs/geo_env/lib/python3.8/site-packages/PIL/Image.py in open(fp, mode) 2859 for message in accept_warnings: 2860 warnings.warn(message) -> 2861 raise UnidentifiedImageError( 2862 "cannot identify image file %r" % (filename if filename else fp) 2863 ) UnidentifiedImageError: cannot identify image file '../data/mosaics/GrandJason_SWRightThird_Nov2019_transparent_mosaic_group1.tif' ``` ### What are your OS, Python and Pillow versions? * OS: Ubuntu 18.04 * Python: 3.8.2 * Pillow: 7.0.0 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> ```python from PIL import Image import os import argparse import numpy as np import json import csv import rasterio import matplotlib import folium from pyproj import Proj, transform %matplotlib inline Image.MAX_IMAGE_PIXELS = 100000000000 # ingest the image infile = "../data/mosaics/GrandJason_SWRightThird_Nov2019_transparent_mosaic_group1.tif" img_dir = '..' + infile.split(".")[2] prj_name = img_dir.split("/")[-1] dataset = rasterio.open(infile) # what is the name of this image img_name = dataset.name print('Image filename: {n}\n'.format(n=img_name)) # How many bands does this image have? num_bands = dataset.count print('Number of bands in image: {n}\n'.format(n=num_bands)) # How many rows and columns? rows, cols = dataset.shape print('Image size is: {r} rows x {c} columns\n'.format(r=rows, c=cols)) # Does the raster have a description or metadata? desc = dataset.descriptions metadata = dataset.meta print('Raster description: {desc}\n'.format(desc=desc)) # What driver was used to open the raster? driver = dataset.driver print('Raster driver: {d}\n'.format(d=driver)) # What is the raster's projection? proj = dataset.crs print('Image projection:') print(proj, '\n') # What is the raster's "geo-transform" gt = dataset.transform print('Image geo-transform:\n{gt}\n'.format(gt=gt)) print('All raster metadata:') print(metadata) print('\n') tile_height = tile_width = 1000 overlap = 80 stride = tile_height - overlap start_num=0 #crop image into tiles def crop(infile, tile_height, tile_width, stride, img_dict, prj_name): im = Image.open(infile) img_width, img_height = im.size print(im.size) print(img_width * img_height / (tile_height - stride) / (tile_width - stride)) count = 0 for r in range(0, img_height-tile_height+1, stride): for c in range(0, img_width-tile_width+1, stride): #tile = im[r:r+100, c:c+100] box = (c, r, c+tile_width, r+tile_height) top_pixel = [c,r] img_dict[prj_name + "---" + str(count) + ".png"] = top_pixel count += 1 yield im.crop(box) #split image into heightxwidth patches img = Image img_dict = {} # create the dir if it doesn't already exist if not os.path.exists(img_dir): os.makedirs(img_dir) # break it up into crops for k, piece in enumerate(crop(infile, tile_height, tile_width, stride, img_dict, prj_name), start_num): img=Image.new('RGB', (tile_height, tile_width), (255, 255, 255)) print(img.size) print(piece.size) img.paste(piece) image_name = prj_name + "---%s.png" % k path=os.path.join(img_dir, image_name) img.save(path) ```
Could be a [BigTIFF](https://www.awaresystems.be/imaging/tiff/bigtiff.html) file, which is not supported by Pillow. The first 4 bytes in BigTIFF files are `b'II\x2B\x00'` or `b'MM\x00\x2B'` > Could be a [BigTIFF](https://www.awaresystems.be/imaging/tiff/bigtiff.html) file, which is not supported by Pillow. The first 4 bytes in BigTIFF files are `b'II\x2B\x00'` or `b'MM\x00\x2B'` None of my tif files are BigTIFF, and they are all way under 4GB size Here is the information of my raster: ```Number of bands in image: 4 Image size is: 18679 rows x 31880 columns Raster description: (None, None, None, None) Raster driver: GTiff Image projection: EPSG:32720 Image geo-transform: | 0.02, 0.00, 632879.80| | 0.00,-0.02, 4341041.62| | 0.00, 0.00, 1.00| All raster metadata: {'driver': 'GTiff', 'dtype': 'uint8', 'nodata': None, 'width': 31880, 'height': 18679, 'count': 4, 'crs': CRS.from_epsg(32720), 'transform': Affine(0.01804, 0.0, 632879.79994, 0.0, -0.01804, 4341041.621540001)} bytearray(b'II+\x00\x08') ``` > `bytearray(b'II+\x00\x08')` That's BigTIFF. Are there any plans to support bigtiff? I'd like to add my name to the list of people who would find it very useful. I've just stumbled upon this issue too. At a first glance, it seems to me that it should be pretty straightforward to modify src/libImaging/TiffDecode.c to handle the BigTIFF format, which is meant to be very closely compatible with the TIFF format. Ah, after working on this for about a day, and getting most of the way to a working solution, I realised that it is probably futile, as BigTIFF files are to a great extent used for medical images, and they will include multiple images within the file (for example, thumbnails). But PIL can only handle one image in a file, so this won't work very well. A better solution is probably to identify BigTIFF files (from the b"MM\x00\x2B" or b"II\x2B\x00" header bytes) and then recommend using something like tifffile to handle the image. If it's of interest, I could upload what I've done so far to github. (It's primarily work on TiffImagePlugin.py and TiffTags.py.) Best wishes! > But PIL can only handle one image in a file, so this won't work very well. Pillow can load multiple images. It opens the file at one image, and then uses `seek()` to navigate to a different image. If you're willing to share what you've done, and an example image, that would be interesting. OK, shall do when I've had a chance to get at least some of it working! I've created PR #6097 to resolve this.
2022-02-28T22:05:19Z
9
python-pillow/Pillow
6,086
python-pillow__Pillow-6086
[ "6084" ]
37d28ce5143d0eb7ca9cd59d24d623855072506a
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -167,9 +167,15 @@ def _seek(self, frame): if self.__frame == 1: self.pyaccess = None if "transparency" in self.info: - self.mode = "RGBA" - self.im.putpalettealpha(self.info["transparency"], 0) - self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG) + if self.mode == "P": + self.im.putpalettealpha(self.info["transparency"], 0) + self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG) + self.mode = "RGBA" + else: + self.im = self.im.convert_transparent( + "LA", self.info["transparency"] + ) + self.mode = "LA" del self.info["transparency"] else: @@ -368,15 +374,18 @@ def load_end(self): if self.__frame == 0: return if self._frame_transparency is not None: - self.im.putpalettealpha(self._frame_transparency, 0) - frame_im = self.im.convert("RGBA") + if self.mode == "P": + self.im.putpalettealpha(self._frame_transparency, 0) + frame_im = self.im.convert("RGBA") + else: + frame_im = self.im.convert_transparent("LA", self._frame_transparency) else: frame_im = self.im.convert("RGB") frame_im = self._crop(frame_im, self.dispose_extent) self.im = self._prev_im self.mode = self.im.mode - if frame_im.mode == "RGBA": + if frame_im.mode in ("LA", "RGBA"): self.im.paste(frame_im, self.dispose_extent, frame_im) else: self.im.paste(frame_im, self.dispose_extent) diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -975,7 +975,9 @@ def convert_transparency(m, v): delete_trns = False # transparency handling if has_transparency: - if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA": + if (self.mode in ("1", "L", "I") and mode in ("LA", "RGBA")) or ( + self.mode == "RGB" and mode == "RGBA" + ): # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( @@ -1564,8 +1566,8 @@ def paste(self, im, box=None, mask=None): also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions - indicated by the mask. You can use either "1", "L" or "RGBA" - images (in the latter case, the alpha band is used as mask). + indicated by the mask. You can use either "1", "L", "LA", "RGBA" + or "RGBa" images (if present, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha @@ -1613,7 +1615,7 @@ def paste(self, im, box=None, mask=None): elif isImageType(im): im.load() if self.mode != im.mode: - if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): + if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im
diff --git a/Tests/images/no_palette_with_transparency.gif b/Tests/images/no_palette_with_transparency.gif new file mode 100644 Binary files /dev/null and b/Tests/images/no_palette_with_transparency.gif differ diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -59,6 +59,17 @@ def test_invalid_file(): GifImagePlugin.GifImageFile(invalid_file) +def test_l_mode_transparency(): + with Image.open("Tests/images/no_palette_with_transparency.gif") as im: + assert im.mode == "L" + assert im.load()[0, 0] == 0 + assert im.info["transparency"] == 255 + + im.seek(1) + assert im.mode == "LA" + assert im.load()[0, 0] == (0, 255) + + def test_optimize(): def test_grayscale(optimize): im = Image.new("L", (1, 1), 0) diff --git a/Tests/test_image_convert.py b/Tests/test_image_convert.py --- a/Tests/test_image_convert.py +++ b/Tests/test_image_convert.py @@ -135,6 +135,10 @@ def test_trns_l(tmp_path): f = str(tmp_path / "temp.png") + im_la = im.convert("LA") + assert "transparency" not in im_la.info + im_la.save(f) + im_rgb = im.convert("RGB") assert im_rgb.info["transparency"] == (128, 128, 128) # undone im_rgb.save(f) diff --git a/Tests/test_image_paste.py b/Tests/test_image_paste.py --- a/Tests/test_image_paste.py +++ b/Tests/test_image_paste.py @@ -67,6 +67,16 @@ def gradient_RGB(self): ], ) + @cached_property + def gradient_LA(self): + return Image.merge( + "LA", + [ + self.gradient_L, + self.gradient_L.transpose(Image.Transpose.ROTATE_90), + ], + ) + @cached_property def gradient_RGBA(self): return Image.merge( @@ -145,6 +155,28 @@ def test_image_mask_L(self): ], ) + def test_image_mask_LA(self): + for mode in ("RGBA", "RGB", "L"): + im = Image.new(mode, (200, 200), "white") + im2 = getattr(self, "gradient_" + mode) + + self.assert_9points_paste( + im, + im2, + self.gradient_LA, + [ + (128, 191, 255, 191), + (112, 207, 206, 111), + (128, 254, 128, 1), + (208, 208, 239, 239), + (192, 191, 191, 191), + (207, 207, 112, 113), + (255, 255, 255, 255), + (239, 207, 207, 239), + (255, 191, 128, 191), + ], + ) + def test_image_mask_RGBA(self): for mode in ("RGBA", "RGB", "L"): im = Image.new(mode, (200, 200), "white")
Pillow no longer reads grayscale multi-frame gifs The following breaks in pillow 9.0.1 but works fine if I downgrade to pillow 8.4.0. My guess is that the new loader that converts to RGB/RGBA when seeking doesn't account for the possibility of a grayscale GIF. ```python from PIL import Image import numpy as np img = Image.open("gray_test.gif") im1 = np.asarray(img) # just showing that the first frame works img.seek(2) # break ``` Stack Trace: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\GifImagePlugin.py", line 133, in seek self._seek(f) File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\GifImagePlugin.py", line 151, in _seek self.load() File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\ImageFile.py", line 264, in load self.load_end() File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\GifImagePlugin.py", line 371, in load_end self.im.putpalettealpha(self._frame_transparency, 0) ValueError: image has no palette ``` Picture for testing: ![gray_test](https://user-images.githubusercontent.com/4402489/155085936-fcbcab8d-2732-4b39-9160-8765866f832c.gif)
I've created PR #6086 to resolve this.
2022-02-22T10:30:31Z
9
python-pillow/Pillow
6,054
python-pillow__Pillow-6054
[ "6027" ]
cac305f8d2db5eca3ce18f8d334a9ff35f9c7fde
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -821,12 +821,6 @@ def load(self): if self.im and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() - if mode == "RGBA": - mode = "RGB" - self.info["transparency"] = arr[3::4] - arr = bytes( - value for (index, value) in enumerate(arr) if index % 4 != 3 - ) palette_length = self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None @@ -837,8 +831,11 @@ def load(self): self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: - self.palette.mode = "RGB" - self.palette.palette = self.im.getpalette()[: palette_length * 3] + palette_mode = "RGBA" if mode.startswith("RGBA") else "RGB" + self.palette.mode = palette_mode + self.palette.palette = self.im.getpalette(palette_mode, palette_mode)[ + : palette_length * len(palette_mode) + ] if self.im: if cffi and USE_CFFI_ACCESS: @@ -1761,8 +1758,8 @@ def putpalette(self, data, rawmode="RGB"): Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). - :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a - mode that can be transformed to "RGB" (e.g. "R", "BGR;15", "RGBA;L"). + :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode + that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette
diff --git a/Tests/test_image_putpalette.py b/Tests/test_image_putpalette.py --- a/Tests/test_image_putpalette.py +++ b/Tests/test_image_putpalette.py @@ -62,3 +62,16 @@ def test_putpalette_with_alpha_values(): im.putpalette(palette_with_alpha_values, "RGBA") assert_image_equal(im.convert("RGBA"), expected) + + +@pytest.mark.parametrize( + "mode, palette", + ( + ("RGBA", (1, 2, 3, 4)), + ("RGBAX", (1, 2, 3, 4, 0)), + ), +) +def test_rgba_palette(mode, palette): + im = Image.new("P", (1, 1)) + im.putpalette(palette, mode) + assert im.palette.colors == {(1, 2, 3, 4): 0}
Palettes with rawmode RGBA;15 don't work ### What did you do? In an attempt to convert a PlayStation TIM image format to a bitmap, I turned to Pillow to handle image processing for me. This proved to be reasonably straightforward, but when operating on 8-bit palettized TIM files, I seem to be unable to preserve transparency. As per [THIS DOCUMENTATION](http://www.psxdev.net/forum/viewtopic.php?t=109) palette entries are RGBA5551 entries, but attempting to use this format with Pillow results in an exception (see the sample code below for more detail). Since palettes with format `'RGBA;15'` (RGBA5551) are reported as supported, while both `'RGBA'` (RGBA8888) and `'RGB;15'` (RGB555) are accepted, I believe this might be a bug. ### What did you expect to happen? I expected `image.putpalette(clut_data, 'RGBA;15')` to succeed and produce a correct image with the alpha channel used. ### What actually happened? `image.putpalette(clut_data, 'RGBA;15')` throws `unrecognized raw mode`. ### What are your OS, Python and Pillow versions? * OS: **Windows 10 21H2** * Python: **3.10.0** * Pillow: **9.0.1**, grabbed from `pip` For a relatively small reproduction, refer to the attached `.zip` with a `.tim` file to convert and run the following example with `python code.py unpack title_gtmode.tim`. Notice `image.putpalette(clut_data, 'RGBA;15')` throws `unrecognized raw mode`, while running it with mode `RGB;15` works as expected and produces a correct image, albeit with transparency data discarded. ```python import sys import struct import os from PIL import Image if len(sys.argv) < 3: exit mode = sys.argv[1].lower() if mode == 'unpack': clut_data = None image_data = None image_width = 0 image_height = 0 with open(sys.argv[2], 'rb') as tim: tag, version = struct.unpack('BB2x', tim.read(4)) if tag == 0x10: if version != 0: sys.exit(f'Unknown TIM file version {version}!') flags = struct.unpack('B3x', tim.read(4))[0] bpp = flags & 3 clp = (flags & 8) != 0 if clp: # Parse CLUT length, x, y, width, height = struct.unpack('IHHHH', tim.read(12)) clut_data = tim.read(length - 12) # Parse image length, x, y, image_width, image_height = struct.unpack('IHHHH', tim.read(12)) image_data = tim.read(length - 12) if image_data: image = Image.frombytes('P', (image_width * 2, image_height), image_data, 'raw', 'P') image.putpalette(clut_data, 'RGBA;15') # 'unrecognized raw mode' exception here name = os.path.splitext(sys.argv[2])[0] image.save(name + '.png') ``` [title_gtmode.zip](https://github.com/python-pillow/Pillow/files/8010648/title_gtmode.zip)
Hi. You're calling `putpalette` with a `rawmode` argument of "RGBA;15". As noted in https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.putpalette > rawmode – The raw mode of the palette. Either “RGB”, “RGBA”, or a mode that can be transformed to “RGB” (e.g. “R”, “BGR;15”, “RGBA;L”). I've created PR #6031 to add this missing transformation (in Pillow development terms, an "unpacker") from RGBA;15 to RGB. Hey, thanks! That looks good. However, does that mean it's impossible to preserve the transparency bit in palettes in my case? TIMs palettes have a single bit signifying if the color is transparent or not, so it should translate to alpha reasonably well when exporting, but I don't know if Pillow lets me do that. I expect this code should let you make use of alpha. ```python image = Image.frombytes('P', (image_width * 2, image_height), image_data, 'raw', 'P') palette = ImagePalette.raw("RGBA;15", clut_data) palette.mode = "RGBA" image.palette = palette name = os.path.splitext('title_gtmode.tim')[0] image.save(name + '.png') ``` Do you have a palette containing transparency that you can test it on? I tried the following example and it throws `unrecognized raw mode` inside `image.save`. An example image containing alphas was 4bpp and not 8bpp so I had to slightly update the code to add support for `P;4` - I also had to swap the nibbles around as else "right" and "left" pixels were in wrong order, and I don't think I can tell Pillow to swap them: ```python import sys import struct import os from PIL import Image, ImagePalette if len(sys.argv) < 3: exit mode = sys.argv[1].lower() if mode == 'unpack': clut_data = None image_data = None image_width = 0 image_height = 0 with open(sys.argv[2], 'rb') as tim: tag, version = struct.unpack('BB2x', tim.read(4)) if tag == 0x10: if version != 0: sys.exit(f'Unknown TIM file version {version}!') flags = struct.unpack('B3x', tim.read(4))[0] bpp = flags & 3 clp = (flags & 8) != 0 if clp: # Parse CLUT length, x, y, width, height = struct.unpack('IHHHH', tim.read(12)) clut_data = tim.read(length - 12) # Parse image length, x, y, width, height = struct.unpack('IHHHH', tim.read(12)) image_data = tim.read(length - 12) if bpp == 0: # 4bit, groups of 4 pixels image_width = width * 4 rawmode = 'P;4' mode = 'P' # TODO: Is there a better way to do it in Pillow? Order of nibbles needs to be swapped image_data = bytes(map(lambda x: ((x & 0xF) << 4) | ((x >> 4) & 0xF), image_data)) elif bpp == 1: # 8bit, groups of 2 pixels image_width = width * 2 rawmode = 'P' mode = 'P' elif bpp == 2: # 16bit, each pixel separate image_width = width rawmode = 'RGB;15' # TODO: Alpha? mode = 'RGB' elif bpp == 3: # 24bit, 3-byte groups # TODO: Verify this image_width = (width * 3) / 2 rawmode = 'RGB' mode = 'RGB' image_height = height if image_data: image = Image.frombytes(mode, (image_width, image_height), image_data, 'raw', rawmode) palette = ImagePalette.raw('RGBA;15', clut_data) palette.mode = 'RGBA' image.palette = palette name = os.path.splitext(sys.argv[2])[0] image.save(name + '.bmp') ``` [GT1_Trial_Mountain.zip](https://github.com/python-pillow/Pillow/files/8017900/GT1_Trial_Mountain.zip)
2022-02-14T09:41:32Z
9
python-pillow/Pillow
5,891
python-pillow__Pillow-5891
[ "5890" ]
2a3867016978f540b258f7653940cc410a4eb85e
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -644,6 +644,22 @@ def __repr__(self): id(self), ) + def _repr_pretty_(self, p, cycle): + """IPython plain text display support""" + + # Same as __repr__ but without unpredicatable id(self), + # to keep Jupyter notebook `text/plain` output stable. + p.text( + "<%s.%s image mode=%s size=%dx%d>" + % ( + self.__class__.__module__, + self.__class__.__name__, + self.mode, + self.size[0], + self.size[1], + ) + ) + def _repr_png_(self): """iPython display hook support
diff --git a/Tests/test_image.py b/Tests/test_image.py --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -88,6 +88,17 @@ def test_sanity(self): # with pytest.raises(MemoryError): # Image.new("L", (1000000, 1000000)) + def test_repr_pretty(self): + class Pretty: + def text(self, text): + self.pretty_output = text + + im = Image.new("L", (100, 100)) + + p = Pretty() + im._repr_pretty_(p, None) + assert p.pretty_output == "<PIL.Image.Image image mode=L size=100x100>" + def test_open_formats(self): PNGFILE = "Tests/images/hopper.png" JPGFILE = "Tests/images/hopper.jpg"
Changing Jupyter plain text output on every cell run ### What did you do? I'm using Pillow to generate simple images in Jupyter environment: ```python from PIL import Image Image.frombuffer('RGB', (16,16), bytes([100]*(16*16))) ``` It works nicely! ![image](https://user-images.githubusercontent.com/510678/146259055-bff41a14-b40d-452e-a354-11c05ce78b58.png) ### What did you expect to happen? I expect every run of the cell produce the same output in the notebook file, to avoid needless changes in Git. ### What actually happened? Every run produces different hash in text representation of the output. For example: `at 0x1075D8370`. ```diff $ git diff test.ipynb diff --git a/test.ipynb b/test.ipynb index f769d4b..a4dd8af 100644 --- a/test.ipynb +++ b/test.ipynb @@ -9,7 +9,7 @@ "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAGUlEQVR4nGPc62fCQApgIkn1qIZRDUNKAwADRwFfBBwAnwAAAABJRU5ErkJggg==", "text/plain": [ - "<PIL.Image.Image image mode=RGB size=16x16 at 0x1075D8370>" + "<PIL.Image.Image image mode=RGB size=16x16 at 0x108C50160>" ] }, "execution_count": 1, ``` Compare with Matplotlib output: ```json "data": { "image/png": "...", "text/plain": [ "<Figure size 432x288 with 1 Axes>" ] } ``` ### What are your OS, Python and Pillow versions? * OS: Mac OS 10.15.6 * Python: 3.9.8 * Pillow: 8.4.0
2021-12-15T20:37:48Z
8.4
python-pillow/Pillow
5,845
python-pillow__Pillow-5845
[ "5590" ]
e1eefe4486401738740a6ad4b3b5998df7a02d5b
diff --git a/src/PIL/IcnsImagePlugin.py b/src/PIL/IcnsImagePlugin.py --- a/src/PIL/IcnsImagePlugin.py +++ b/src/PIL/IcnsImagePlugin.py @@ -337,23 +337,28 @@ def _save(im, fp, filename): entries = [] for type, size in sizes.items(): stream = size_streams[size] - entries.append({"type": type, "size": len(stream), "stream": stream}) + entries.append( + {"type": type, "size": HEADERSIZE + len(stream), "stream": stream} + ) # Header fp.write(MAGIC) - fp.write(struct.pack(">i", sum(entry["size"] for entry in entries))) + file_length = HEADERSIZE # Header + file_length += HEADERSIZE + 8 * len(entries) # TOC + file_length += sum(entry["size"] for entry in entries) + fp.write(struct.pack(">i", file_length)) # TOC fp.write(b"TOC ") fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE)) for entry in entries: fp.write(entry["type"]) - fp.write(struct.pack(">i", HEADERSIZE + entry["size"])) + fp.write(struct.pack(">i", entry["size"])) # Data for entry in entries: fp.write(entry["type"]) - fp.write(struct.pack(">i", HEADERSIZE + entry["size"])) + fp.write(struct.pack(">i", entry["size"])) fp.write(entry["stream"]) if hasattr(fp, "flush"):
diff --git a/Tests/test_file_icns.py b/Tests/test_file_icns.py --- a/Tests/test_file_icns.py +++ b/Tests/test_file_icns.py @@ -1,8 +1,9 @@ import io +import os import pytest -from PIL import IcnsImagePlugin, Image, features +from PIL import IcnsImagePlugin, Image, _binary, features from .helper import assert_image_equal, assert_image_similar_tofile @@ -38,6 +39,11 @@ def test_save(tmp_path): assert reread.size == (1024, 1024) assert reread.format == "ICNS" + file_length = os.path.getsize(temp_file) + with open(temp_file, "rb") as fp: + fp.seek(4) + assert _binary.i32be(fp.read(4)) == file_length + def test_save_append_images(tmp_path): temp_file = str(tmp_path / "temp.icns")
App icns modification breaks the icon display on macOS <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? Modified `*.icns` file inside the app on MacOS ### What did you expect to happen? Updated icon to be visible using Finder/Get Info. ### What actually happened? After upgrading Pillow to 8.3.0 version, updating `*.icns` file inside the application on MacOS, makes the app icon not visible/invalid in Finder, though all the icons are visible if you open the `icns` file directly. ### What are your OS, Python and Pillow versions? * OS: MacOS 10.15 Catalina * Python: 3.7.7, 3.9.7 * Pillow: 8.3.0 or 8.3.1, 8.4.0 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> ```python with Image.open(image_path) as image: draw=ImageDraw.Draw(image) draw.rectangle([(0,0), (image.width,image.height)], fill=(255,0,0)) image.save(image.filename) ```
Using an application on my computer, I'm not able to replicate this. Could you upload the original ICNS file? What version of macOS do you have? @radarhere Sorry about the invalid example, I've rechecked it and it requires drawing prior to saving in order to break the icon (Finder may cache the old icon, so it's easier to see the change using Get Info option on the application). Not really sure if it's related to https://github.com/python-pillow/Pillow/pull/4526 change, but the issue appeared after upgrading to Pillow 8.3.0 @radarhere I've updated the example section of description. It was tested with both MacOS 10.15 Catalina and 11.6 Big Sur. The issue is present in 8.4.0 as well.
2021-11-20T03:18:00Z
8.4
python-pillow/Pillow
5,839
python-pillow__Pillow-5839
[ "5838" ]
d6e42f330710ddb854ba56eda7a025b4025fab1e
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -89,7 +89,10 @@ ARTIST = 315 PREDICTOR = 317 COLORMAP = 320 +TILEWIDTH = 322 +TILELENGTH = 323 TILEOFFSETS = 324 +TILEBYTECOUNTS = 325 SUBIFD = 330 EXTRASAMPLES = 338 SAMPLEFORMAT = 339 @@ -1649,6 +1652,7 @@ def _save(im, fp, filename): }.items(): ifd.setdefault(tag, value) + blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS] if libtiff: if "quality" in encoderinfo: quality = encoderinfo["quality"] @@ -1680,7 +1684,7 @@ def _save(im, fp, filename): # BITSPERSAMPLE, etc), passing arrays with a different length will result in # segfaults. Block these tags until we add extra validation. # SUBIFD may also cause a segfault. - blocklist = [ + blocklist += [ REFERENCEBLACKWHITE, SAMPLEFORMAT, STRIPBYTECOUNTS, @@ -1753,6 +1757,8 @@ def _save(im, fp, filename): raise OSError(f"encoder error {s} when writing image file") else: + for tag in blocklist: + del ifd[tag] offset = ifd.save(fp) ImageFile._save(
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -920,6 +920,23 @@ def test_strip_planar_16bit_RGBa(self): with Image.open("Tests/images/tiff_strip_planar_16bit_RGBa.tiff") as im: assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGBa_target.png") + @pytest.mark.parametrize("compression", (None, "jpeg")) + def test_block_tile_tags(self, compression, tmp_path): + im = hopper() + out = str(tmp_path / "temp.tif") + + tags = { + TiffImagePlugin.TILEWIDTH: 256, + TiffImagePlugin.TILELENGTH: 256, + TiffImagePlugin.TILEOFFSETS: 256, + TiffImagePlugin.TILEBYTECOUNTS: 256, + } + im.save(out, exif=tags, compression=compression) + + with Image.open(out) as reloaded: + for tag in tags.keys(): + assert tag not in reloaded.getexif() + def test_old_style_jpeg(self): with Image.open("Tests/images/old-style-jpeg-compression.tif") as im: assert_image_equal_tofile(im, "Tests/images/old-style-jpeg-compression.png")
Three TIFF tags cause display issues in GIS software When I run my GeoTIFF though Pillow while trying to preserve the TIFF info I end up with 3 additional TIFF tags in the output (`StripOffsets`, `RowsPerStrip`, `StripByteCounts`). The resulting output GeoTIFF is now displayed incorrectly in the GIS software `ESRI ArcMap` (all cell values are now `NoData`), but is displayed correctly with `Pillow` or `Matplotlib`. The input GeoTIFF image is produced with `ESRI ArcMap` and does not have the 3 extra TIFF tags. This could of course be an issue with `ESRI ArcMap`, but I believe the 3 Pillow generated TIFF tags might be wrong. They show up as: ``` StripOffsets = (810,) RowsPerStrip = (40,) StripByteCounts = (6400,) ``` Input GeoTIFF: [dem_input.zip](https://github.com/python-pillow/Pillow/files/7557972/dem_input.zip) ```python from PIL import Image EXTRA_TIFF_TAGS = {"StripOffsets" : 273, "RowsPerStrip" : 278, "StripByteCounts" : 279} image_input = Image.open("dem_input.tif") print([TAG in image_input.tag._tagdata for TAG in EXTRA_TIFF_TAGS.values()]) # [False, False, False] image_input.save("dem_output.tif", tiffinfo = image_input.tag) image_output = Image.open("dem_output.tif") print([TAG in image_output.tag._tagdata for TAG in EXTRA_TIFF_TAGS.values()]) # [True, True, True] print([image_output.tag[TAG] for TAG in EXTRA_TIFF_TAGS.values()]) # [(810,), (40,), (6400,)] ```
I suspect that you're much more likely to be losing the geo metadata or converting data types than seeing those tags cause an error. I'd recommend checking the metadata with `gdalinfo`. And generally, depending on what you're doing, `gdal` (command line/python) or `rasterio` (better python bindings to gdal) will probably be better for interfacing with rasters. When I use `gdalinfo`, the results are identical on the input and the output images. What Pillow version are you using? I am using version `8.4.0`: ```python >>> import PIL >>> PIL.__version__ '8.4.0' ``` I can see that there is quite a large size difference between my input dem and output dem, so something is happening (66975 byte vs 7210 byte). It just seems a bit weird to me that the output has not lost any tags and gained three new ones, but is way smaller in size. Here is the produced output from the earlier code: [dem_output.zip](https://github.com/python-pillow/Pillow/files/7558811/dem_output.zip) I am aware that `gdal` is better suited for GeoTIFF, but after some testing of different rasters I was surprised to see that I was able to retain almost all TIFF tags to preserve a working GeoTIFF raster after using Pillow. For me personally it would be really convenient for my preferred workflow if all TIFF tags were correctly retained, but I guess that is far from the focus of Pillow? Part of the problem is that StripOffsets, RowsPerStrip and StripByteCounts are not data that just happens to also be in the same file as the image - they are instructions for how to read the image. https://www.awaresystems.be/imaging/tiff/tifftags/rowsperstrip.html > TIFF image data can be organized into strips for faster random access and efficient I/O buffering. Pillow would be using strips with the intention to create a better image. You might suggest that Pillow shouldn't write images in strips if the supplied tags don't mention it. But what if a user had manually created a list of a few TIFF tags they wanted saved, and hadn't even thought about strips? We would then be punishing them by saving a less-optimal image. These three tags are actually _mandatory_ for strip-based TIFF-compliant images, even if you have just the one strip. Your original image is tile-based, and has these mandatory tags instead: ``` TileWidth : 128 TileLength : 128 TileOffsets : 674 TileByteCounts : 65536 ``` Normally TIFF-compliant readers should be able to deal with both tile-based and strip-based files. One other thing: your code keeps the original tile-based tags, which should be removed when writing as strip-based, try that. The way it is, you end up with an "invalid" TIFF file. > Pillow should set `ROWSPERSTRIP` to something more reasonable than `im.size[1]` or allow to specify the value. Photoshop fails when `ROWSPERSTRIP` is too large. https://github.com/python-pillow/Pillow/issues/2866#issuecomment-377812187 Maybe this is of relevance? > Maybe this is of relevance? Nope, see above. As for the size difference: tile-based will always write full tiles (128x128 in this case) even for your 40x40 image, padded with 0s. No padding is necessary for strip-based writing. 128x128 / (40x40) = 10.24 factor difference you're seeing. Pillow should probably include a mechanism for automatic removal of tile-based tags if writing as strips.
2021-11-18T11:02:45Z
8.4
python-pillow/Pillow
5,696
python-pillow__Pillow-5696
[ "5695" ]
d50052a75c4d0d17d3d37c24a4558c9e0736f0e8
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1130,7 +1130,9 @@ def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", dither, palette.im) - return self._new(im) + new_im = self._new(im) + new_im.palette = palette.palette.copy() + return new_im im = self._new(self.im.quantize(colors, method, kmeans))
diff --git a/Tests/test_image_quantize.py b/Tests/test_image_quantize.py --- a/Tests/test_image_quantize.py +++ b/Tests/test_image_quantize.py @@ -63,6 +63,7 @@ def test_quantize_no_dither(): converted = image.quantize(dither=0, palette=palette) assert_image(converted, "P", converted.size) + assert converted.palette.palette == palette.palette.palette def test_quantize_dither_diff():
PNG palette quantized save functionality different between 8.1.0 and 8.3.1 ### What did you do? Create a palette, quantize an image using this palette and save it. ### What did you expect to happen? The palette information is stored correctly. I.e. the list of RGB values is the same in the saved image. E.g. [0, 0, 0, 209, 254, 76, 217, 3, 3, 10, 66, 192,...] ### What actually happened? The list of RGB values is corrupted. E.g. [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3,...] ### What are your OS, Python and Pillow versions? * OS: Tested on Windows and Azure Databricks (Ubuntu) * Python: 3.6 & 3.8 * Pillow: 8.3.1 has the issue ```python from PIL import Image from itertools import cycle import numpy as np palette = [0, 0, 0, 209, 254, 76, 217, 3, 3, 10, 66, 192] # palette must contain 768 values (256 * 3) # repeat the colours until we get there color_iter = cycle(palette) expanded_palette_format = [] while True: expanded_palette_format.append(next(color_iter)) if len(expanded_palette_format) == 768: break assert len(expanded_palette_format) == 768 palette_image = Image.new('P', (16, 16)) palette_image.putpalette(expanded_palette_format) # a new image that we want to apply the palette to im_to_palette = np.array( [ [[0, 0, 0,],[209, 254, 76], [217, 3, 3], [10, 66, 192]], [[0, 0, 0,],[209, 254, 76], [217, 3, 3], [10, 66, 192]], [[0, 0, 0,],[209, 254, 76], [217, 3, 3], [10, 66, 192]], [[0, 0, 0,],[209, 254, 76], [217, 3, 3], [10, 66, 192]] ], np.uint8 ) im = Image.fromarray(im_to_palette).quantize(palette=palette_image, dither=0) im.save(r"test.png") saved_im = Image.open(r"test.png") assert im.getpalette() == saved_im.getpalette() # AssertionError ``` Please note that if I specifically pass the 'GIF' argument on save, it has the expected behaviour. ```python im.save(r"test.png", "GIF") saved_im = Image.open(r"test.png") assert im.getpalette() == saved_im.getpalette() ```
2021-08-30T14:38:21Z
8.3
python-pillow/Pillow
5,756
python-pillow__Pillow-5756
[ "5656" ]
2d7c487cf8fbee80428248138d5632a5da1758f9
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -271,11 +271,9 @@ def _seek(self, frame): Image._decompression_bomb_check(dispose_size) # by convention, attempt to use transparency first - color = ( - frame_transparency - if frame_transparency is not None - else self.info.get("background", 0) - ) + color = self.info.get("transparency", frame_transparency) + if color is None: + color = self.info.get("background", 0) self.dispose = Image.core.fill("P", dispose_size, color) else: # replace with previous contents
diff --git a/Tests/images/dispose_bgnd_transparency.gif b/Tests/images/dispose_bgnd_transparency.gif new file mode 100644 Binary files /dev/null and b/Tests/images/dispose_bgnd_transparency.gif differ diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -337,6 +337,13 @@ def test_dispose_background(): pass +def test_dispose_background_transparency(): + with Image.open("Tests/images/dispose_bgnd_transparency.gif") as img: + img.seek(2) + px = img.convert("RGBA").load() + assert px[35, 30][3] == 0 + + def test_transparent_dispose(): expected_colors = [(2, 1, 2), (0, 1, 0), (2, 1, 2)] with Image.open("Tests/images/transparent_dispose.gif") as img:
AnimGIF not transparent The frames of the down below animated GIF are not transparent (first frame works). Testcase: ````python import base64, io import PIL.Image animgif = ''' R0lGODlhJgAgAPdEAAIBAQsKChkGBCUdBy4lByoqKUw5AFlFAltJE2dNAkVFRU1OTlZVVWFiYoIgAIRjAJJxApx1AaJ6AK2MJMGRAM+bANKdANagANmjAOKqBOewC+a5L//MM/7XNoqKipqamvPz8/b29ru7uiMiIL29vdHR0dnZ2f/RKjY2NUQzAHhhGWpqaqd9APO+GPnGLf///4SEhCEfGHpcAHJzc9M0ALKGAL2OAO+6Gf/ZOOzr63NWAW9xcqYmANqnDt2rE8qjKd6zLf/YNr/DxOfo6BYSBOHh4aJ9CM7Ozv/cN8ecGn1gA7KJCn5+gtzc3BoZFTELAD49PEkOAFETAmxTAG5ubtk2AP/RNZaWlqSkpOTk4/r6+3h4eLYnANbW1qSEIZGRkcfHx+q0Eubm5jcqAUU2C8+cBP/XMdbX2GdTFsHBwTAuJkE6JbGwsNzb2nBsY/TBKcQwAM00ALaKAcqXAOGuFfbDI//ONJ2dnTAsGz05LUA7LUhDOf/PNtTU0+OwF+q5HxEUFjoZARwmKS0xMmkNAHsPAGgTAGxjSZcbAOM1AO8zAP84AP/ROK2hfp+hptXPveq8MMiWAM2ZAOi1HNClI/39/f81APHx8bCKHD0wAv/SMf3GIb6TDjwwDoVqG+azGv/cMP/OJfbILHRaAZN2IKysrCEGAFA9AXYaBIcZANWiBlYJAIBnHIpvHo5yH6uxs2BOFFxcW6qCAko7D0g3AmZnbPbIMoxtFMCWE92qD41rAv/kObi4uNOiC6eHJeGyJO7AMLuYJrW1tJ1+ H/O+IPnONW9ZFvnCHcTDwUU3Efk2AYdoEKF/GPXEMGxpYr/Av25VDHtfDkpBI1hLITQ6QjJEWDRMaEJSaMAnAOUvAfozAMCZJe++Llp4ln+CipKQia+rn7a4vYu66qTZ/9/bzuXh09vc4Mvy//r37ff28fH////MKv3KMdSsLKaDHv3LNc+gFs+mKQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFyABEACwAAAAAGwAgAAAI/wCJCBxIkAiJHAUTKkyoZdAXEyZALJwosM8WBVCqWatGbcEdiRQHZom1QBiIFy/UnRsnrhu1DyGJiIDy7IUWc+E+wKh1zdrGAAvETBSGwpE3aiMGEKCFAFq0ZbcSHBgDBWRBE4CcEDjAjBI3Dh3MBOnQAUedCxhkNFDIAME2W2StdLDDoS5YO3bozLlg4E5BMAjG0rUD6YfduhN+WHFRxkKNGAgHugnWwW6HYQE2WOGweYAKHHx87DXwaGA6acA217UCxMthDkAg4Z0U6cKDRgPLIVB9uPJhvHj/zLHA4tBAZMZ8v35Nl4Md2hZs6Bn4LPny687t+JlTgUKegeRgKf/H/rvHcDl7BqKbZss5ebt2GFuw7YzgIcMbyDavu58DoxuSSGDBKWwQBA4azZCBwASQWDFWBw9WRokOYxxgwxohEPQCFED88UAKY8yCBiuukNKKCgiQkcIUNWQwhQcJCZFMMSeEMQcLD4ySwBQ6PBCBDfNhEAEUGSbkAQLF 4MDBG8TcoAEGqlhgQQWSYMACHiZM9M0slBzTwiQ+TEllBRfYpkYfIaXhxAGykInBmxZEAgFVl4QUwhYCRBFIhVOMMsUpgUgRhRMeVDIRCApIkY0yNHCBCCqGRJEKHDRUwcMTDWihEKJSKGPJp9isYoopAQiAyCJx0ADHE7EoFIsU2nyPms0qAcywAwALvBLAqTSo+sQWBX3xhCKfciHAAm28EEIpWbwgBCCFKJKqsaWI5AQXn6YSwB0ovVCKAligdIYghCQSRxUOFADSCoYsYgkigpTQ7QsMAIBCt0MMYkgV/EYBYwkBoMJDKgA0gMUVCN+xAgBQfICwIzMAIAUqqUjhhBgkxELFxhx37PHHGzfQRUAAIfkECRQATgAsFgAPAA4AEQAACNsAnQgUaOLIi4EIBx5RgEKEkxBNDiIcMuLWAxRDFATYkdDDLBy9YiiAtSRGDoQKfAXxQYTIhl4DigwEMeIHjh4BEHSwYXLmCCBBcAHwdeLBAoQhCvxAsoTIr1wDmCAsEcOALAsUMEggEkDIwRlEECAgIsMCrSQ3dDDgpWAAEBy7VByQNcBWiwgoPgiAhQTHBCI1IBDgoGFULBEOCNhyYSTCBRthExAhEYKGACUXLFyoYIFFCgAOBfIAIKtFhgsXMjwYEQKhqQAqSOmScYBIqYQrFDRgsKAWjBIIAwIAIfkECRQAMQAsFQAMAA4AFAAACP8AYwgUqOVIm4EIEcJwoqZEjC5gXiTEMiBJAioiiBC5IvDCAzdQvIBiMWIEJggKBFo49cHJBjNLACDoEAGKQApr RBBgpykCgAknHjAQOMVDGgIczCgJsKFFig8CoYQ4MsDFCSWnNhkBwEagiRAeABiIUKZCBSUDnBSJ0aQAGU8qiEhgkelNGAMezlBB0wFJh04SEiBAoiHBFhILvCCxgmYMhgMI1lkYg4UBEwSaPkmgcEFCgAMEFIB4wsAJhAtmK1hgMaYACIFPFBDh1CLDBQwXMq0YyEUACiJoVEw5MACKmIFVHBRg82XLli8iQiCsUiWKh4QJHTiQ4iQL9oFUwjcF6PI9RkAAIfkECTIAKAAsEAAGABQAGgAACP8AUQgcSBCFGDAgCiosCGIGlDsCc2ghaGdhg1kQnBTxEGBBiIUDjxABdiwTAwKYBpAQuGGhB1g4jhkAMKFkKRRW7HAoRoxgLFI46mQiYksDAREK51iwoYfBMBw3iCDoQCGGGIJ86MypQCHPz11+iLjblEDBQqU19jDIJEuVHAtzBgD4otDChQNECMwacArDlAh/IBRYOXCOBBsBvNjZFYxA3GAn5jj5UPCArgHFOmwgMCpuu2OyRvAqmAFvO024RlmwQCDZ5S0JBWLAEAFKAwQYKljQLYdWgBkEKwjEY6KIkwdhctnNgBgZQQsC+wi8AsAYJiO6ZAxosDC2QGG1FkBJWdAAy8SF51GE6CICi4gSH0E2SA9y4ZNY9evDebIl/0IaXAhwk38ExVGFAwV4R2AVDEbhAYEDSYFKKlI4kQWEKFChIRUNdFFfQAAh+QQJCgCjACwLAAYAGAAaAAAI/wBHCRTYAUedCxhkNBjIsGHDDnbs0JlzwcAdhxgHTvhh xUUZCzVi5MiIcYAKHHx8UDTwiKRDIJAiTop04UEjlw0jRvwzxwKLQzgZ2uHAwc5MCzb0jNJypA1OohH9zKlAIc8oGE7UlBjVBUwlh0SL9ugpZw+WAUkSUBFBhMgHsEU9WqjpBooXUCxGjMAEQcFAqEQZ3ZgjwYKBD042aFoCAIGmCEqDBBnYgQMlHWMOUFhDggAHTUYATDjxgIFDBGRSTKmRYYqHNATsmFESYEOLFG8bRrAxF0MEKCGODBB1QomBTaHZOLRQQRIGFnhMhPAAwECEMhUqKBngpMhASZIqXNWoqaZPkwJkPKkgIoFFpjdhDHhoGAnCGCiXzuxA0wFJh04SJIAAEhoksEVDgUgRhRMeiLCAF0hYgcYYGByAQCgWjIFFQ3DQUAUPTzDAhGOfSEDBBRIEcAABCoDQECKLxEEDHCE6AcEF2VXg0xgFuNhQAIhYQsOMTyhABCctZIDQBZmsgJEQgBSiiIxcCIACEWioMMUBA0AhBkYvnCEIIYnEUYUDBbDxxRZbfCFCCBm98MIQgxhSxZ1RzBfUKFdc4cgMAEjhgANSOJHFnlQkqqiiDXSRUUAAIfkECTIAIwAsCwAGABIAGgAACP8AOXQwE6RDBxx1LmCQ0WCEw4d2OEgUaMcOnTkXDNx56HCixAk/rLgoY6FGjBwcN1jhsHKAiiB2crGoYeARR48cgECqmORAglGNRrzo6NFKxA0D0KQwcIhBAWEjcEbkoAKWGVkDiCCQoSAqTg7NCATDwQnAAEhyCmj5mvOslbIqzEgY9IJtuwHNzBgBECyU joYSp0oEMgBYh2VEmvUYUGqEwYIG32EKEMEHBRYaHgCAAoKVK1KtVCAYEGCAaVkVpiThNObKqARTdMhIMOAHBxyzZEAgwKgFwxsaMFiQYMAVkg4TBtiYgsCMhgRbfKiqUIFFAjRBOIx6gAECEWYPiKS3uWABg3kJRHBZsHChgoUERAJAPTBl1JRTgQQQuJBhvQUNOqDgECKoGBJFKnDAYQoZwXBSgywyEIGFQ6uYYkoAAiCyCBdSPAEAICgsIMJDM+wAwAKvBICIMnDw4IApsRTB0QshlJLFC0IAUogicdDAhQCNPfRCKQpg8cILZwhCSCJxVOFAASAIyQAAKBz5whCDGFLFllF48NAdK2z2wRVXODIDAFKgkooUTmThEBVwximnnA104VBAACH5BAkKALAALAsABgAYABoAAAj/ADl0MBOkQwccdS5gkNEAlsOHEB3a4UBRoB07dOZcMHAnoseKFCf8sOKijIUaMXJ4hLjBCgeXA1Tg4ONDo4FHKx+C5AAE0sVJkS48aJTT4c6LF//MscDiUFFYRynaAWrBhh5YWo60+biTw0U/cypQyAMLhhM1JWB1AVMJalevPZbK2YNlQJIEVEQQIfLB7dGSFoS6geIFFIsRIzBBUODXK0VGN+ZIsGDgg5MNmpYAQKApwtUgoA124EBJx5gDFNaQIMBBkxEAE048YACLlStSrVQgIJNiSo0MUzykIWDHjJIAG1qk6DsqwRQdDyLYCIwhApQQRwaIOqHEwKbXbGDd/9CAQZUFCxUkYWCBx0QIDwAMRChToYKSAU6K +EAvSVKFC0Kp0UcTBZDhiQpESMBCJm+EYYAHCmGAgQWRQDAGFJecsQMaHSDRQScSJIAAEhoksMUBU4wyxSmBSBGFEx6IsIAXSFiBxhgYHIBAKBaMgQUiqBgSRSpw0FAFD08wwARnn0hAwQUSBHAAAQqAsIoppgQgACKLxEEDHEk6AcEF9VXA1BgFgADLDDsAsMArASBiCQ1fPqEAEZy0kIFCF2SygkMvhFBKFi8IAUghinjJhQAoEIGGClMcMAAUYgBaigJYvPDCGYIQkkgcVThQABtfbLHFFyKE8NALDACAgqYvDCoxiCFV1BqFB0XdsQIAUHxwxRWOzACAFA44IIUTWeRExbLMNttsA13kFBAAIfkECTIAIgAsCwAGABsAGgAACP8AOXQwE6RDBxx1LmCQ0UCEw4cQI9rhQFGgHTt05lwwcCeix4cVKU74YcdFGQs1YuT46HGDFQ4vB6jAwceHRgOPWEYMyQHIhouTIl140CgiCDArIfK0MrEYsTkWWByCmEMBERQr2SATwXMiBzuToNrQA7EBLDop7mwZQIQET4p2+GSsQCHPwyJOgIQaVQAPnQRb3sLtAVXOnodYyFhZJwPAsFBTZggueXKos4ce0ARZNwXAhha0vsANyejGHAkWTrHBjAbHukydOlgYcMZgQYMcKOkYc4DCmhAPPxwwc+zArWMJAJVg5YpUKxUIyKSYUiPDFA8PzywIQIuFhTkUpoz/QTEqwRQdDyLYsKAwAhTgIrAQMeZFBZE5U2CZ6THghgYMqlhgQQUVXMACHiY4VMIgEwSB BBAEUDCGF5pgMIYPA1YgSYFDqdHHQ0KM0A4OwAygg4WuHCOLEwphgIEFkUAwBhQgUMWAJ+v0IksFFjzAHREwHDDFKFOcEogUUTjhQSUQkUCELAPOwSMLAzSECCqGRJEKHDRUwcMTDWhR1hjwEJOBQjUQsdoqppgSgACILBIHDXA8EQtEQ0BBBAIInJIJEVs4NMMOACzwSgBx0kDnE4E+FEIaWHhwBRttPPRCCKVk8YIQgBSiyJxcCFCKThC9UIoCWLzwwhmCEJJIHFU4OFBAjaSK8AIDAKCg6gtDDGJIFcBGgV2td6wAABQfXHGFIzMAIAUqqUjhRBa1UmHttdhi20AXtQYEACH5BAkKALAALAsABgAYABoAAAj/ADl0MBOkQwccdS5gkNEAlsOHEB3a4UBRoB07dOZcMHAnoseKFCf8sOKijIUaMXJ4hLjBCgeXA1Tg4ONDo4FHKx+C5AAE0sVJkS48aJTT4c6LF//MscDiUFFYRynaAWrBhh5YWo60+biTw0U/cypQyAMLhhM1JWB1AVMJalevPZbK2YNlQJIEVEQQIfLB7dGSFoS6geIFFIsRIzBBUODXK0VGN+ZIsGDgg5MNmpYAQKApwtUgoA124EBJx5gDFNaQIMBBkxEAE048YACLlStSrVQgIJNiSo0MUzykIWDHjJIAG1qk6DsqwRQdDyLYCIwhApQQRwaIOqHEwKbXbGDd/9CAQZUFCxUkYWCBx0QIDwAMRChToYKSAU6K+EAvSVKFC0Kp0UcTBZDhiQpESMBCJm+EYYAHCmGAgQWRQDAG FJecsQMaHSDRQScSJIAAEhoksMUBU4wyxSmBSBGFEx6IsIAXSFiBxhgYHIBAKBaMgQUiqBgSRSpw0FAFD08wwARnn0hAwQUSBHAAAQqAsIoppgQgACKLxEEDHEk6AcEF9VXA1BgFgADLDDsAsMArASBiCQ1fPqEAEZy0kIFCF2SygkMvhFBKFi8IAUghinjJhQAoEIGGClMcMAAUYgBaigJYvPDCGYIQkkgcVThQABtfbLHFFyKE8NALDACAgqYvDCoxiCFV1BqFB0XdsQIAUHxwxRWOzACAFA44IIUTWeRExbLMNttsA13kFBAAIfkEBRQAWwAsCwAGABkAGgAACP8AOXQwE6RDBxx1LmCQ0WCLw4cQH9rhQFGgHTt05lwwcCeixy0VKU74YcdFGQs1YuT4CHGDFQ4vB6jAwceHRgOPWD4MyQHIhouTIl140EinQ55WJhYjNscCi0NGQYacyMHOpKY29ETlSdEOn4wVKOTZyrVqj6Zy9pDlWfLkUGcOTRx54XEqRUY35kiwcIrNliMKUIjYEqIJ3S1BEhvswIGSjjEHKKwJMWTErQcohigIsMMhK1ekWqlAQCbFlBoZpnjY4mEWjl4xFMBaonLLqARTdDyIYMOCwghQQmxR4AuJDyJENvQaUGTLDQ0YVFmwUKHCBRZ4TGy5NCIejh4BEHT/sFHbB3VJkqwPVdPHIXcgQXAB8HXiwQKHCjFgsBAJwhgoIDwUQgE/ILEEEb/kMgATDh0wxShTnBKIFFE44UElDvXhxCmylEEBBhIQEcAzlSCCiiFRpAIH DVXw8EQDWsxABAIIECHDBbQk0YIODPCyiimmBCAAIovEQQMcTygwABAd7KLCAbIMYAsxEaDwwQw7ALDAKwEgYgkNRwoACxIdTEBEDRAQwIEGo8QiwgshlJLFC0IAUogiRjpAgC0uGBHBBTbMmAARJITwQikKYPHCC2cIQkgiRgqgxAXTVeBUCgAMtsULDACAwqIvDDGIIVW0CIAsN2TgWwYPjCDcFnesLQAAFB9ccYUjMwAghQMOBKnCMLoocQARpTxExbHIJovsCgo0wMACtcBQAkQBAQA7''' with PIL.Image.open(io.BytesIO(base64.b64decode(animgif)), 'r') as img: for index, frame in enumerate(PIL.ImageSequence.Iterator(img)): img.save('/tmp/not-transparent-'+str(index)+'.png', 'PNG') ````
Experimenting, I find that prioritising the global transparency over frame transparency when replacing with background color fixes this. ```diff diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index db6944267..128afc428 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -271,11 +271,9 @@ class GifImageFile(ImageFile.ImageFile): Image._decompression_bomb_check(dispose_size) # by convention, attempt to use transparency first - color = ( - frame_transparency - if frame_transparency is not None - else self.info.get("background", 0) - ) + color = self.info.get("transparency", frame_transparency) + if color is None: + color = self.info.get("background", 0) self.dispose = Image.core.fill("P", dispose_size, color) else: # replace with previous contents ``` Is the image data that you've provided able to be included as part of our test suite, and distributed under our Pillow license? @radarhere Thanks a lot for all your efforts. Yes, the GIF image is license free (created in house).
2021-10-11T22:49:17Z
8.3
python-pillow/Pillow
5,647
python-pillow__Pillow-5647
[ "5643" ]
eee0953bb33a5648c454b4628801034071d4f07d
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2479,6 +2479,8 @@ def getdata(self): raise ValueError("missing method data") im = new(self.mode, size, fillcolor) + if self.mode == "P" and self.palette: + im.palette = self.palette.copy() im.info = self.info.copy() if method == MESH: # list of quads
diff --git a/Tests/test_image_transform.py b/Tests/test_image_transform.py --- a/Tests/test_image_transform.py +++ b/Tests/test_image_transform.py @@ -32,6 +32,11 @@ def test_info(self): new_im = im.transform((100, 100), transform) assert new_im.info["comment"] == comment + def test_palette(self): + with Image.open("Tests/images/hopper.gif") as im: + transformed = im.transform(im.size, Image.AFFINE, [1, 0, 0, 0, 1, 0]) + assert im.palette.palette == transformed.palette.palette + def test_extent(self): im = hopper("RGB") (w, h) = im.size
Problem rotating P images ```python from PIL import Image import random img = Image.open('test.png') rate = random.randint(30, 330) img = img.rotate(rate) img.show() img.save('test_rotate.png') ``` ![test](https://user-images.githubusercontent.com/37957822/127455530-f7437db9-b2df-4b89-be5b-5582b67b4eb8.png) ![test_rotate](https://user-images.githubusercontent.com/37957822/127455537-05a6a378-4ba9-4018-a22f-5f2dabbe6eea.png)
The image generated by rotating the picture is a binary image If you're looking for an immediate solution, you can convert it to RGB after opening. ```python from PIL import Image import random img = Image.open('test.png').convert('RGB') rate = random.randint(30, 330) img = img.rotate(rate) img.show() img.save('test_rotate.png') ``` Thank you for your answer. It's useful This problem was introduced by #5552
2021-07-30T10:14:15Z
8.3
python-pillow/Pillow
5,609
python-pillow__Pillow-5609
[ "5608" ]
83c05aaf8daa930086257eb38b254f06808d13e5
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -1117,12 +1117,12 @@ def _write_multiple_frames(im, fp, chunk, rawmode): and prev_disposal == encoderinfo.get("disposal") and prev_blend == encoderinfo.get("blend") ): - duration = encoderinfo.get("duration", 0) - if duration: + frame_duration = encoderinfo.get("duration", 0) + if frame_duration: if "duration" in previous["encoderinfo"]: - previous["encoderinfo"]["duration"] += duration + previous["encoderinfo"]["duration"] += frame_duration else: - previous["encoderinfo"]["duration"] = duration + previous["encoderinfo"]["duration"] = frame_duration continue else: bbox = None
diff --git a/Tests/test_file_apng.py b/Tests/test_file_apng.py --- a/Tests/test_file_apng.py +++ b/Tests/test_file_apng.py @@ -433,7 +433,9 @@ def test_apng_save_duration_loop(tmp_path): # test removal of duplicated frames frame = Image.new("RGBA", (128, 64), (255, 0, 0, 255)) - frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250]) + frame.save( + test_file, save_all=True, append_images=[frame, frame], duration=[500, 100, 150] + ) with Image.open(test_file) as im: im.load() assert im.n_frames == 1
type list doesn't define __round__ method <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? I saved .apng file ### What did you expect to happen? Running with no exception ### What actually happened? I got "type list doesn't define \_\_round\_\_ method" error in function "_write_multiple_frames" https://github.com/python-pillow/Pillow/blob/83c05aaf8daa930086257eb38b254f06808d13e5/src/PIL/PngImagePlugin.py#L1060 https://github.com/python-pillow/Pillow/blob/83c05aaf8daa930086257eb38b254f06808d13e5/src/PIL/PngImagePlugin.py#L1152 ### What are your OS, Python and Pillow versions? * OS: MacOS * Python: 3.8.2 * Pillow: 8.3.1 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. -->
2021-07-13T03:48:36Z
8.3
python-pillow/Pillow
5,572
python-pillow__Pillow-5572
[ "5571" ]
53ce23c74972d43971585a0d2f2e8ce850964fac
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -681,7 +681,7 @@ def _repr_png_(self): raise ValueError("Could not save to PNG for display") from e return b.getvalue() - def __array__(self): + def __array__(self, dtype=None): # numpy array interface support import numpy as np @@ -700,7 +700,7 @@ def __array__(self): class ArrayData: __array_interface__ = new - return np.array(ArrayData()) + return np.array(ArrayData(), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]
diff --git a/Tests/test_image_array.py b/Tests/test_image_array.py --- a/Tests/test_image_array.py +++ b/Tests/test_image_array.py @@ -14,6 +14,10 @@ def test(mode): ai = numpy.array(im.convert(mode)) return ai.shape, ai.dtype.str, ai.nbytes + def test_with_dtype(dtype): + ai = numpy.array(im, dtype=dtype) + assert ai.dtype == dtype + # assert test("1") == ((100, 128), '|b1', 1600)) assert test("L") == ((100, 128), "|u1", 12800) @@ -27,6 +31,9 @@ def test(mode): assert test("RGBA") == ((100, 128, 4), "|u1", 51200) assert test("RGBX") == ((100, 128, 4), "|u1", 51200) + test_with_dtype(numpy.float64) + test_with_dtype(numpy.uint8) + with Image.open("Tests/images/truncated_jpeg.jpg") as im_truncated: with pytest.raises(OSError): numpy.array(im_truncated)
Pillow 8.3 and NumPy Throws exception with Pillow 8.3: `TypeError: __array__() takes 1 positional argument but 2 were given` ````python with PIL.Image.open(filepath) as img: numpy.array( img, dtype=numpy.float32 ) ````
What version of Python are you using? What version of numpy? Same problem here. Python 3.7.4 numpy 1.21.0 workaround: ```python with PIL.Image.open(filepath) as img: numpy.array(img).astype(np.float32) ``` Works with just about anything. The problem is that pillow newly implemented `__array__`, but only without arguments. Numpy requires `__array__` to take an optional dtype argument. This is used e.g. by numpy.array when the user passes a dtype argument. This should be with just about any numpy/python version. fails with python 3.8 + 3.9, numpy 1.20 + 1.21 I'll send a patch. We are seeing errors in `3.{6,7,8,9}` Same issue in https://github.com/hyperspy/hyperspy/runs/2961516889 for all python version >=3.6 using the `imageio` library: ```python # Apply palette > frame_paletted = np.array(im, np.uint8) E TypeError: __array__() takes 1 positional argument but 2 were given /opt/hostedtoolcache/Python/3.9.5/x64/lib/python3.9/site-packages/imageio/plugins/pillow.py:745: TypeError ``` The python 3.6 build is with numpy 1.17.1
2021-07-01T11:11:56Z
8.3
python-pillow/Pillow
5,557
python-pillow__Pillow-5557
[ "5548" ]
70ef50cf72992ab6c9330412d6f1340c593e2d8f
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -269,9 +269,14 @@ def _seek(self, frame): dispose_size = (x1 - x0, y1 - y0) Image._decompression_bomb_check(dispose_size) - self.dispose = Image.core.fill( - "P", dispose_size, self.info.get("background", 0) + + # by convention, attempt to use transparency first + color = ( + frame_transparency + if frame_transparency is not None + else self.info.get("background", 0) ) + self.dispose = Image.core.fill("P", dispose_size, color) else: # replace with previous contents if self.im: @@ -317,6 +322,12 @@ def _seek(self, frame): if self.palette: self.mode = "P" + def load_prepare(self): + if not self.im and "transparency" in self.info: + self.im = Image.core.fill(self.mode, self.size, self.info["transparency"]) + + super(GifImageFile, self).load_prepare() + def tell(self): return self.__frame
diff --git a/Tests/images/first_frame_transparency.gif b/Tests/images/first_frame_transparency.gif new file mode 100644 Binary files /dev/null and b/Tests/images/first_frame_transparency.gif differ diff --git a/Tests/images/transparent_dispose.gif b/Tests/images/transparent_dispose.gif new file mode 100644 Binary files /dev/null and b/Tests/images/transparent_dispose.gif differ diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -298,6 +298,12 @@ def test_eoferror(): im.seek(n_frames - 1) +def test_first_frame_transparency(): + with Image.open("Tests/images/first_frame_transparency.gif") as im: + px = im.load() + assert px[0, 0] == im.info["transparency"] + + def test_dispose_none(): with Image.open("Tests/images/dispose_none.gif") as img: try: @@ -331,6 +337,16 @@ def test_dispose_background(): pass +def test_transparent_dispose(): + expected_colors = [(2, 1, 2), (0, 1, 0), (2, 1, 2)] + with Image.open("Tests/images/transparent_dispose.gif") as img: + for frame in range(3): + img.seek(frame) + for x in range(3): + color = img.getpixel((x, 0)) + assert color == expected_colors[frame][x] + + def test_dispose_previous(): with Image.open("Tests/images/dispose_prev.gif") as img: try:
AnimGIF not transparent Loading some anim-GIFs result in opaque background. Example to reproduce: PNG has a black border on the right inside (should be transparent): ````python import base64, io import PIL.Image animgif = 'R0lGODlhJgAgAPdEAAIBAQsKChkGBCUdBy4lByoqKUw5AFlFAltJE2dNAkVFRU1OTlZVVWFiYoIgAIRjAJJxApx1AaJ6AK2MJMGRAM+bANKdANagANmjAOKqBOewC+a5L//MM/7XNoqKipqamvPz8/b29ru7uiMiIL29vdHR0dnZ2f/RKjY2NUQzAHhhGWpqaqd9APO+GPnGLf///4SEhCEfGHpcAHJzc9M0ALKGAL2OAO+6Gf/ZOOzr63NWAW9xcqYmANqnDt2rE8qjKd6zLf/YNr/DxOfo6BYSBOHh4aJ9CM7Ozv/cN8ecGn1gA7KJCn5+gtzc3BoZFTELAD49PEkOAFETAmxTAG5ubtk2AP/RNZaWlqSkpOTk4/r6+3h4eLYnANbW1qSEIZGRkcfHx+q0Eubm5jcqAUU2C8+cBP/XMdbX2GdTFsHBwTAuJkE6JbGwsNzb2nBsY/TBKcQwAM00ALaKAcqXAOGuFfbDI//ONJ2dnTAsGz05LUA7LUhDOf/PNtTU0+OwF+q5HxEUFjoZARwmKS0xMmkNAHsPAGgTAGxjSZcbAOM1AO8zAP84AP/ROK2hfp+hptXPveq8MMiWAM2ZAOi1HNClI/39/f81APHx8bCKHD0wAv/SMf3GIb6TDjwwDoVqG+azGv/cMP/OJfbILHRaAZN2IKysrCEGAFA9AXYaBIcZANWiBlYJAIBnHIpvHo5yH6uxs2BOFFxcW6qCAko7D0g3AmZnbPbIMoxtFMCWE92qD41rAv/kObi4uNOiC6eHJeGyJO7AMLuYJrW1tJ1+H/O+IPnONW9ZFvnCHcTDwUU3Efk2AYdoEKF/GPXEMGxpYr/Av25VDHtfDkpBI1hLITQ6QjJEWDRMaEJSaMAnAOUvAfozAMCZJe++Llp4ln+CipKQia+rn7a4vYu66qTZ/9/bzuXh09vc4Mvy//r37ff28fH////MKv3KMdSsLKaDHv3LNc+gFs+mKQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFyABEACwAAAAAGwAgAAAI/wCJCBxIkAiJHAUTKkyoZdAXEyZALJwosM8WBVCqWatGbcEdiRQHZom1QBiIFy/UnRsnrhu1DyGJiIDy7IUWc+E+wKh1zdrGAAvETBSGwpE3aiMGEKCFAFq0ZbcSHBgDBWRBE4CcEDjAjBI3Dh3MBOnQAUedCxhkNFDIAME2W2StdLDDoS5YO3bozLlg4E5BMAjG0rUD6YfduhN+WHFRxkKNGAgHugnWwW6HYQE2WOGweYAKHHx87DXwaGA6acA217UCxMthDkAg4Z0U6cKDRgPLIVB9uPJhvHj/zLHA4tBAZMZ8v35Nl4Md2hZs6Bn4LPny687t+JlTgUKegeRgKf/H/rvHcDl7BqKbZss5ebt2GFuw7YzgIcMbyDavu58DoxuSSGDBKWwQBA4azZCBwASQWDFWBw9WRokOYxxgwxohEPQCFED88UAKY8yCBiuukNKKCgiQkcIUNWQwhQcJCZFMMSeEMQcLD4ySwBQ6PBCBDfNhEAEUGSbkAQLF4MDBG8TcoAEGqlhgQQWSYMACHiZM9M0slBzTwiQ+TEllBRfYpkYfIaXhxAGykInBmxZEAgFVl4QUwhYCRBFIhVOMMsUpgUgRhRMeVDIRCApIkY0yNHCBCCqGRJEKHDRUwcMTDWihEKJSKGPJp9isYoopAQiAyCJx0ADHE7EoFIsU2nyPms0qAcywAwALvBLAqTSo+sQWBX3xhCKfciHAAm28EEIpWbwgBCCFKJKqsaWI5AQXn6YSwB0ovVCKAligdIYghCQSRxUOFADSCoYsYgkigpTQ7QsMAIBCt0MMYkgV/EYBYwkBoMJDKgA0gMUVCN+xAgBQfICwIzMAIAUqqUjhhBgkxELFxhx37PHHGzfQRUAAIfkECRQATgAsFgAPAA4AEQAACNsAnQgUaOLIi4EIBx5RgEKEkxBNDiIcMuLWAxRDFATYkdDDLBy9YiiAtSRGDoQKfAXxQYTIhl4DigwEMeIHjh4BEHSwYXLmCCBBcAHwdeLBAoQhCvxAsoTIr1wDmCAsEcOALAsUMEggEkDIwRlEECAgIsMCrSQ3dDDgpWAAEBy7VByQNcBWiwgoPgiAhQTHBCI1IBDgoGFULBEOCNhyYSTCBRthExAhEYKGACUXLFyoYIFFCgAOBfIAIKtFhgsXMjwYEQKhqQAqSOmScYBIqYQrFDRgsKAWjBIIAwIAIfkECRQAMQAsFQAMAA4AFAAACP8AYwgUqOVIm4EIEcJwoqZEjC5gXiTEMiBJAioiiBC5IvDCAzdQvIBiMWIEJggKBFo49cHJBjNLACDoEAGKQAprRBBgpykCgAknHjAQOMVDGgIczCgJsKFFig8CoYQ4MsDFCSWnNhkBwEagiRAeABiIUKZCBSUDnBSJ0aQAGU8qiEhgkelNGAMezlBB0wFJh04SEiBAoiHBFhILvCCxgmYMhgMI1lkYg4UBEwSaPkmgcEFCgAMEFIB4wsAJhAtmK1hgMaYACIFPFBDh1CLDBQwXMq0YyEUACiJoVEw5MACKmIFVHBRg82XLli8iQiCsUiWKh4QJHTiQ4iQL9oFUwjcF6PI9RkAAIfkECTIAKAAsEAAGABQAGgAACP8AUQgcSBCFGDAgCiosCGIGlDsCc2ghaGdhg1kQnBTxEGBBiIUDjxABdiwTAwKYBpAQuGGhB1g4jhkAMKFkKRRW7HAoRoxgLFI46mQiYksDAREK51iwoYfBMBw3iCDoQCGGGIJ86MypQCHPz11+iLjblEDBQqU19jDIJEuVHAtzBgD4otDChQNECMwacArDlAh/IBRYOXCOBBsBvNjZFYxA3GAn5jj5UPCArgHFOmwgMCpuu2OyRvAqmAFvO024RlmwQCDZ5S0JBWLAEAFKAwQYKljQLYdWgBkEKwjEY6KIkwdhctnNgBgZQQsC+wi8AsAYJiO6ZAxosDC2QGG1FkBJWdAAy8SF51GE6CICi4gSH0E2SA9y4ZNY9evDebIl/0IaXAhwk38ExVGFAwV4R2AVDEbhAYEDSYFKKlI4kQWEKFChIRUNdFFfQAAh+QQJCgCjACwLAAYAGAAaAAAI/wBHCRTYAUedCxhkNBjIsGHDDnbs0JlzwcAdhxgHTvhhxUUZCzVi5MiIcYAKHHx8UDTwiKRDIJAiTop04UEjlw0jRvwzxwKLQzgZ2uHAwc5MCzb0jNJypA1OohH9zKlAIc8oGE7UlBjVBUwlh0SL9ugpZw+WAUkSUBFBhMgHsEU9WqjpBooXUCxGjMAEQcFAqEQZ3ZgjwYKBD042aFoCAIGmCEqDBBnYgQMlHWMOUFhDggAHTUYATDjxgIFDBGRSTKmRYYqHNATsmFESYEOLFG8bRrAxF0MEKCGODBB1QomBTaHZOLRQQRIGFnhMhPAAwECEMhUqKBngpMhASZIqXNWoqaZPkwJkPKkgIoFFpjdhDHhoGAnCGCiXzuxA0wFJh04SJIAAEhoksEVDgUgRhRMeiLCAF0hYgcYYGByAQCgWjIFFQ3DQUAUPTzDAhGOfSEDBBRIEcAABCoDQECKLxEEDHCE6AcEF2VXg0xgFuNhQAIhYQsOMTyhABCctZIDQBZmsgJEQgBSiiIxcCIACEWioMMUBA0AhBkYvnCEIIYnEUYUDBbDxxRZbfCFCCBm98MIQgxhSxZ1RzBfUKFdc4cgMAEjhgANSOJHFnlQkqqiiDXSRUUAAIfkECTIAIwAsCwAGABIAGgAACP8AOXQwE6RDBxx1LmCQ0WCEw4d2OEgUaMcOnTkXDNx56HCixAk/rLgoY6FGjBwcN1jhsHKAiiB2crGoYeARR48cgECqmORAglGNRrzo6NFKxA0D0KQwcIhBAWEjcEbkoAKWGVkDiCCQoSAqTg7NCATDwQnAAEhyCmj5mvOslbIqzEgY9IJtuwHNzBgBECyUjoYSp0oEMgBYh2VEmvUYUGqEwYIG32EKEMEHBRYaHgCAAoKVK1KtVCAYEGCAaVkVpiThNObKqARTdMhIMOAHBxyzZEAgwKgFwxsaMFiQYMAVkg4TBtiYgsCMhgRbfKiqUIFFAjRBOIx6gAECEWYPiKS3uWABg3kJRHBZsHChgoUERAJAPTBl1JRTgQQQuJBhvQUNOqDgECKoGBJFKnDAYQoZwXBSgywyEIGFQ6uYYkoAAiCyCBdSPAEAICgsIMJDM+wAwAKvBICIMnDw4IApsRTB0QshlJLFC0IAUogicdDAhQCNPfRCKQpg8cILZwhCSCJxVOFAASAIyQAAKBz5whCDGFLFllF48NAdK2z2wRVXODIDAFKgkooUTmThEBVwximnnA104VBAACH5BAkKALAALAsABgAYABoAAAj/ADl0MBOkQwccdS5gkNEAlsOHEB3a4UBRoB07dOZcMHAnoseKFCf8sOKijIUaMXJ4hLjBCgeXA1Tg4ONDo4FHKx+C5AAE0sVJkS48aJTT4c6LF//MscDiUFFYRynaAWrBhh5YWo60+biTw0U/cypQyAMLhhM1JWB1AVMJalevPZbK2YNlQJIEVEQQIfLB7dGSFoS6geIFFIsRIzBBUODXK0VGN+ZIsGDgg5MNmpYAQKApwtUgoA124EBJx5gDFNaQIMBBkxEAE048YACLlStSrVQgIJNiSo0MUzykIWDHjJIAG1qk6DsqwRQdDyLYCIwhApQQRwaIOqHEwKbXbGDd/9CAQZUFCxUkYWCBx0QIDwAMRChToYKSAU6K+EAvSVKFC0Kp0UcTBZDhiQpESMBCJm+EYYAHCmGAgQWRQDAGFJecsQMaHSDRQScSJIAAEhoksMUBU4wyxSmBSBGFEx6IsIAXSFiBxhgYHIBAKBaMgQUiqBgSRSpw0FAFD08wwARnn0hAwQUSBHAAAQqAsIoppgQgACKLxEEDHEk6AcEF9VXA1BgFgADLDDsAsMArASBiCQ1fPqEAEZy0kIFCF2SygkMvhFBKFi8IAUghinjJhQAoEIGGClMcMAAUYgBaigJYvPDCGYIQkkgcVThQABtfbLHFFyKE8NALDACAgqYvDCoxiCFV1BqFB0XdsQIAUHxwxRWOzACAFA44IIUTWeRExbLMNttsA13kFBAAIfkECTIAIgAsCwAGABsAGgAACP8AOXQwE6RDBxx1LmCQ0UCEw4cQI9rhQFGgHTt05lwwcCeix4cVKU74YcdFGQs1YuT46HGDFQ4vB6jAwceHRgOPWEYMyQHIhouTIl140CgiCDArIfK0MrEYsTkWWByCmEMBERQr2SATwXMiBzuToNrQA7EBLDop7mwZQIQET4p2+GSsQCHPwyJOgIQaVQAPnQRb3sLtAVXOnodYyFhZJwPAsFBTZggueXKos4ce0ARZNwXAhha0vsANyejGHAkWTrHBjAbHukydOlgYcMZgQYMcKOkYc4DCmhAPPxwwc+zArWMJAJVg5YpUKxUIyKSYUiPDFA8PzywIQIuFhTkUpoz/QTEqwRQdDyLYsKAwAhTgIrAQMeZFBZE5U2CZ6THghgYMqlhgQQUVXMACHiY4VMIgEwSBBBAEUDCGF5pgMIYPA1YgSYFDqdHHQ0KM0A4OwAygg4WuHCOLEwphgIEFkUAwBhQgUMWAJ+v0IksFFjzAHREwHDDFKFOcEogUUTjhQSUQkUCELAPOwSMLAzSECCqGRJEKHDRUwcMTDWhR1hjwEJOBQjUQsdoqppgSgACILBIHDXA8EQtEQ0BBBAIInJIJEVs4NMMOACzwSgBx0kDnE4E+FEIaWHhwBRttPPRCCKVk8YIQgBSiyJxcCFCKThC9UIoCWLzwwhmCEJJIHFU4OFBAjaSK8AIDAKCg6gtDDGJIFcBGgV2td6wAABQfXHGFIzMAIAUqqUjhRBa1UmHttdhi20AXtQYEACH5BAkKALAALAsABgAYABoAAAj/ADl0MBOkQwccdS5gkNEAlsOHEB3a4UBRoB07dOZcMHAnoseKFCf8sOKijIUaMXJ4hLjBCgeXA1Tg4ONDo4FHKx+C5AAE0sVJkS48aJTT4c6LF//MscDiUFFYRynaAWrBhh5YWo60+biTw0U/cypQyAMLhhM1JWB1AVMJalevPZbK2YNlQJIEVEQQIfLB7dGSFoS6geIFFIsRIzBBUODXK0VGN+ZIsGDgg5MNmpYAQKApwtUgoA124EBJx5gDFNaQIMBBkxEAE048YACLlStSrVQgIJNiSo0MUzykIWDHjJIAG1qk6DsqwRQdDyLYCIwhApQQRwaIOqHEwKbXbGDd/9CAQZUFCxUkYWCBx0QIDwAMRChToYKSAU6K+EAvSVKFC0Kp0UcTBZDhiQpESMBCJm+EYYAHCmGAgQWRQDAGFJecsQMaHSDRQScSJIAAEhoksMUBU4wyxSmBSBGFEx6IsIAXSFiBxhgYHIBAKBaMgQUiqBgSRSpw0FAFD08wwARnn0hAwQUSBHAAAQqAsIoppgQgACKLxEEDHEk6AcEF9VXA1BgFgADLDDsAsMArASBiCQ1fPqEAEZy0kIFCF2SygkMvhFBKFi8IAUghinjJhQAoEIGGClMcMAAUYgBaigJYvPDCGYIQkkgcVThQABtfbLHFFyKE8NALDACAgqYvDCoxiCFV1BqFB0XdsQIAUHxwxRWOzACAFA44IIUTWeRExbLMNttsA13kFBAAIfkEBRQAWwAsCwAGABkAGgAACP8AOXQwE6RDBxx1LmCQ0WCLw4cQH9rhQFGgHTt05lwwcCeixy0VKU74YcdFGQs1YuT4CHGDFQ4vB6jAwceHRgOPWD4MyQHIhouTIl140EinQ55WJhYjNscCi0NGQYacyMHOpKY29ETlSdEOn4wVKOTZyrVqj6Zy9pDlWfLkUGcOTRx54XEqRUY35kiwcIrNliMKUIjYEqIJ3S1BEhvswIGSjjEHKKwJMWTErQcohigIsMMhK1ekWqlAQCbFlBoZpnjY4mEWjl4xFMBaonLLqARTdDyIYMOCwghQQmxR4AuJDyJENvQaUGTLDQ0YVFmwUKHCBRZ4TGy5NCIejh4BEHT/sFHbB3VJkqwPVdPHIXcgQXAB8HXiwQKHCjFgsBAJwhgoIDwUQgE/ILEEEb/kMgATDh0wxShTnBKIFFE44UElDvXhxCmylEEBBhIQEcAzlSCCiiFRpAIHDVXw8EQDWsxABAIIECHDBbQk0YIODPCyiimmBCAAIovEQQMcTygwABAd7KLCAbIMYAsxEaDwwQw7ALDAKwEgYgkNRwoACxIdTEBEDRAQwIEGo8QiwgshlJLFC0IAUogiRjpAgC0uGBHBBTbMmAARJITwQikKYPHCC2cIQkgiRgqgxAXTVeBUCgAMtsULDACAwqIvDDGIIVW0CIAsN2TgWwYPjCDcFnesLQAAFB9ccYUjMwAghQMOBKnCMLoocQARpTxExbHIJovsCgo0wMACtcBQAkQBAQA7' with PIL.Image.open(io.BytesIO(base64.b64decode(animgif)), 'r') as img: img.save( '/tmp/blackborder.png', 'PNG' ) ````
The first frame has a `dispose_extent` of (0, 0, 27, 32) - which is not the full size of the image. #3434 would fix this image, by setting the uncovered parts of the first frame to transparency. I just don't understand why this is the solution on a theoretical level, as the [spec](https://www.w3.org/Graphics/GIF/spec-gif89a.txt) states that > The Background Color is the color used for those pixels on the screen that are not covered by an image. rather than the transparency. @RLaursen since you're thinking a lot about GIFs at the moment, I'll ask you. See this 75px by 50px image. ![out](https://user-images.githubusercontent.com/3112309/122673953-5c9f7680-d216-11eb-8680-a115c52d87c5.gif) The first frame (well, the only frame) has an Image Descriptor with an Image Left Position of (25, 0) - in Pillow terms, those are the `x0` and `y0` of `dispose_extent`. So the leftmost 25 pixels of the image are not covered. Since the spec states that the background color should be "used for those pixels on the screen that are not covered by an image", and the background color is #0f0 (0 index, meaning the first entry in the palette), I would think those pixels should be green. Instead, the browser renders those pixels as transparent. Any thoughts as to why this is? This is not a question about how Pillow behaves, rather a question about how GIFs behave. @radarhere That's certainly interesting, and I agree that the uncovered portion on the left should be the background color. Even if the background index was the same as the transparency index, which it isn't, I still think it should display the background color, purely based on the 89a specs. My guess is that viewers are generally set up to only use the background color when disposal method 2 is used, even though this seems like an incorrect interpretation of the format. Perhaps Pillow should mirror this behavior, if only to display GIFs consistently. yeah, strangely enough, even with the transparency flag off, transparency is used for uncovered canvas ![weirdy](https://user-images.githubusercontent.com/67596484/122839858-bacb6880-d2ad-11eb-9b50-7968225d359a.gif) I'm also trying to get Pillow working better with animated GIFs. Not much progress yet. @radarhere has already noticed some problems with the spec. E.g., when method 3 is used in the first frame, to dispose to previous, when there is no previous? Or what happens with disposal method 2 when there's no GCT, so no background color? Apparently the interpretation "in the wild" may follow historic conventions. A clue: http://giflib.sourceforge.net/whatsinagif/bits_and_bytes.html says of the background color index: "GIFLIB supports reading and setting this byte, but modern viewers and browsers generally have no use for it." (Also says of the size in the Logical Screen Descriptor: "The canvas width and height are usually ignored by modern viewers.") A page apparently authored when animated GIFs were a new thing: http://www6.uniovi.es/gifanim/gifabout.htm says this: "The Logical Screen Block also chooses one of the colors in the Global Color Table to be the Background color of the screen. This color selection is ignored by Netscape Navigator. If a GIF's background area shows through, Navigator displays the color set in the BGCOLOR of the page's body or, if none is specified, the background color set in the menus under OPTIONS/GENERAL PREFERENCES/COLORS. Now, of course, the question arises; how do I get it to be transparent? Well, this SHOULDN'T work, but it does. Apparently, if Netscape's decoder finds a Control block (it must be first, before any images) with Transparency turned on (any color) the background of the GIF will be transparent. This will allows background GIFs to fill in the logical screen background." It's not clear to me what Navigator did when no transparency was set, since it ignored the background color set in the LSD. But I'm guessing browsers may have always ignored it. That page also says "If your logical screen is larger than your image, you will have space around the image when displayed." But doesn't say what was in that space. Maybe just the page bgcolor or browser preference. That page also says "The logical screen area should be large enough to display all of your individual frames in it. If an image in the GIF file is larger than the logical screen or, by its positioning, extends beyond the screen, the portion that is off-screen will not be displayed." Which contradicts Pillow's decision to expand the size when a frame exceeds its boundaries. I opened 75x50 GIF in several programs. Irfanview indicated its size as 50x50, consistent with what giflib whatsinagif says. It does the same with @rlaursen's GIF above. I haven't found any more information about how programs actually interpret these features (background, transparency, image size, disposal methods.) I'll keep digging.
2021-06-25T12:38:46Z
8.2
python-pillow/Pillow
5,554
python-pillow__Pillow-5554
[ "5553" ]
52856bceb71f3e9f774f9593c735094fe8ade092
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -465,7 +465,7 @@ class ImageFileDirectory_v2(MutableMapping): """ - def __init__(self, ifh=b"II\052\0\0\0\0\0", prefix=None): + def __init__(self, ifh=b"II\052\0\0\0\0\0", prefix=None, group=None): """Initialize an ImageFileDirectory. To construct an ImageFileDirectory from a real file, pass the 8-byte @@ -485,6 +485,7 @@ def __init__(self, ifh=b"II\052\0\0\0\0\0", prefix=None): self._endian = "<" else: raise SyntaxError("not a TIFF IFD") + self.group = group self.tagtype = {} """ Dictionary of tag types """ self.reset() @@ -516,7 +517,10 @@ def named(self): Returns the complete tag dictionary, with named tags where possible. """ - return {TiffTags.lookup(code).name: value for code, value in self.items()} + return { + TiffTags.lookup(code, self.group).name: value + for code, value in self.items() + } def __len__(self): return len(set(self._tagdata) | set(self._tags_v2)) @@ -541,7 +545,7 @@ def __setitem__(self, tag, value): def _setitem(self, tag, value, legacy_api): basetypes = (Number, bytes, str) - info = TiffTags.lookup(tag) + info = TiffTags.lookup(tag, self.group) values = [value] if isinstance(value, basetypes) else value if tag not in self.tagtype: @@ -758,7 +762,7 @@ def load(self, fp): for i in range(self._unpack("H", self._ensure_read(fp, 2))[0]): tag, typ, count, data = self._unpack("HHL4s", self._ensure_read(fp, 12)) - tagname = TiffTags.lookup(tag).name + tagname = TiffTags.lookup(tag, self.group).name typname = TYPES.get(typ, "unknown") msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})" @@ -825,7 +829,7 @@ def tobytes(self, offset=0): ifh = b"II\x2A\x00\x08\x00\x00\x00" else: ifh = b"MM\x00\x2A\x00\x00\x00\x08" - ifd = ImageFileDirectory_v2(ifh) + ifd = ImageFileDirectory_v2(ifh, group=tag) values = self._tags_v2[tag] for ifd_tag, ifd_value in values.items(): ifd[ifd_tag] = ifd_value @@ -834,7 +838,7 @@ def tobytes(self, offset=0): values = value if isinstance(value, tuple) else (value,) data = self._write_dispatch[typ](self, *values) - tagname = TiffTags.lookup(tag).name + tagname = TiffTags.lookup(tag, self.group).name typname = "ifd" if is_ifd else TYPES.get(typ, "unknown") msg = f"save: {tagname} ({tag}) - type: {typname} ({typ})" msg += " - value: " + ( diff --git a/src/PIL/TiffTags.py b/src/PIL/TiffTags.py --- a/src/PIL/TiffTags.py +++ b/src/PIL/TiffTags.py @@ -33,7 +33,7 @@ def cvt_enum(self, value): return self.enum.get(value, value) if self.enum else value -def lookup(tag): +def lookup(tag, group=None): """ :param tag: Integer tag number :returns: Taginfo namedtuple, From the TAGS_V2 info if possible, @@ -42,7 +42,11 @@ def lookup(tag): """ - return TAGS_V2.get(tag, TagInfo(tag, TAGS.get(tag, "unknown"))) + if group is not None: + info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None + else: + info = TAGS_V2.get(tag) + return info or TagInfo(tag, TAGS.get(tag, "unknown")) ## @@ -213,6 +217,19 @@ def lookup(tag): 50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one 50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006 } +TAGS_V2_GROUPS = { + # ExifIFD + 34665: { + 36864: ("ExifVersion", UNDEFINED, 1), + 40960: ("FlashPixVersion", UNDEFINED, 1), + 40965: ("InteroperabilityIFD", LONG, 1), + 41730: ("CFAPattern", UNDEFINED, 1), + }, + # GPSInfoIFD + 34853: {}, + # InteroperabilityIFD + 40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)}, +} # Legacy Tags structure # these tags aren't included above, but were in the previous versions @@ -371,6 +388,10 @@ def _populate(): TAGS_V2[k] = TagInfo(k, *v) + for group, tags in TAGS_V2_GROUPS.items(): + for k, v in tags.items(): + tags[k] = TagInfo(k, *v) + _populate() ##
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py --- a/Tests/test_file_tiff_metadata.py +++ b/Tests/test_file_tiff_metadata.py @@ -378,6 +378,20 @@ def test_too_many_entries(): pytest.warns(UserWarning, lambda: ifd[277]) +def test_tag_group_data(): + base_ifd = TiffImagePlugin.ImageFileDirectory_v2() + interop_ifd = TiffImagePlugin.ImageFileDirectory_v2(group=40965) + for ifd in (base_ifd, interop_ifd): + ifd[2] = "test" + ifd[256] = 10 + + assert base_ifd.tagtype[256] == 4 + assert interop_ifd.tagtype[256] != base_ifd.tagtype[256] + + assert interop_ifd.tagtype[2] == 7 + assert base_ifd.tagtype[2] != interop_ifd.tagtype[256] + + def test_empty_subifd(tmp_path): out = str(tmp_path / "temp.jpg")
EXIF tag `InteropVersion` has wrong type ## What did you do? Open an image with Pillow and save it with its exif data. ## What did you expect to happen? The content of the exif field `InteropVersion` must be the same in both files. ## What actually happened? The type of `InteropVersion` field value is set to `TiffTags.BYTE` (1) by Pillow where it should be of type `TiffTags.UNDEFINED` (7) to conform to standard. Some software might rely on that field to assess the validity of the file. ## What are your OS, Python and Pillow versions? - OS: Ubuntu 20.04 - Python: 3.8.5 - Pillow: 8.2.0 + fix from #5490 ```python from PIL import Image #open a jpeg image im = Image.open("original.jpg") # save it with original parameters, but it doesn't change the problem to use default values im.save("copy.jpg", exif=im.getexif(), quality=95, progressive=True, subsampling="4:4:4") ``` Original image: ![pixelated](https://user-images.githubusercontent.com/4659733/123107550-ef6c2b00-d439-11eb-8a3e-458a8a651f08.jpg) Result image: ![original_copy](https://user-images.githubusercontent.com/4659733/123107631-00b53780-d43a-11eb-9e4b-f6a9b469724f.jpg) Extract of the EXIF data from the original file (using `exiftool -D -s original.jpg`): ``` 40962 ExifImageWidth : 1920 40963 ExifImageHeight : 692 1 InteropIndex : R98 - DCF basic file (sRGB) 2 InteropVersion : 0100 ``` In the saved file (using `exiftool -D -s copy.jpg`): ``` 40962 ExifImageWidth : 1920 40963 ExifImageHeight : 692 1 InteropIndex : R98 - DCF basic file (sRGB) 2 InteropVersion : 48 49 48 48 ```
A workaround, from a user perspective, is to save file to a buffer, then seek and change the type of the IFD tag, and save the file.
2021-06-24T10:26:31Z
8.2
python-pillow/Pillow
5,549
python-pillow__Pillow-5549
[ "4830" ]
384a4bf01ec8d631dcde2c3246bd08e37fa1b7cd
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -830,7 +830,7 @@ def load(self): arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) - self.im.putpalette(mode, arr) + palette_length = self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info: @@ -841,6 +841,7 @@ def load(self): self.palette.mode = "RGBA" else: self.palette.mode = "RGB" + self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: if cffi and USE_CFFI_ACCESS:
diff --git a/Tests/test_file_tga.py b/Tests/test_file_tga.py --- a/Tests/test_file_tga.py +++ b/Tests/test_file_tga.py @@ -65,10 +65,15 @@ def roundtrip(original_im): roundtrip(original_im) -def test_palette_depth_16(): +def test_palette_depth_16(tmp_path): with Image.open("Tests/images/p_16.tga") as im: assert_image_equal_tofile(im.convert("RGB"), "Tests/images/p_16.png") + out = str(tmp_path / "temp.png") + im.save(out) + with Image.open(out) as reloaded: + assert_image_equal_tofile(reloaded.convert("RGB"), "Tests/images/p_16.png") + def test_id_field(): # tga file with id field
PIL doesn't seem to handle the color map correctly in some color indexed TGA files Please see my question in [Stack Overflow](https://stackoverflow.com/questions/63151906/is-there-any-other-attribute-that-affetcts-how-colors-are-displayed-on-an-indexe) where I explain everything in greater detail and more importantly, where Mark Setchell explains why he thinks there is a bug in PIL when handling some color indexed TGA files. Basically, I am working with a sample color indexed TGA file to test a script that would invert its colors. But before any of that, the issue is that PIL doesn't seem to handle the color map correctly when open it and the values of the color palette end up being wrong. These are the sample files: [CCM8.TGA](https://www.fileformat.info/format/tga/sample/c36e10e31828483d832ef67561e20d5a/download) and [UCM8.TGA](https://www.fileformat.info/format/tga/sample/34402cd832c3456eb82628798f54709a/download). And you will see that if you open show any of them: ```python from PIL import Image Image.open('CCM8.TGA').show() ``` PIL shows: ![pQ6IH](https://user-images.githubusercontent.com/1219020/89067243-ce54a480-d366-11ea-91f1-f7c95b843d27.png) When it should be: ![IpPCy](https://user-images.githubusercontent.com/1219020/89067319-f512db00-d366-11ea-9af7-e7c813be8669.png) As I said, I wrote all the details on that post. If you want me to submit more information here, please let me know. I am using Pillow 7.0 on Fedora 32 and Python 3.8.
Do you have images that demonstrate this problem, that are able to be added to the test suite under the Pillow license? I have recreated those images which you can add to the test suite. [TGA_samples.zip](https://github.com/python-pillow/Pillow/files/5013124/TGA_samples.zip) Thank you. I've created #5396 to fix an unrelated bug mentioned in the StackOverflow answer. I've created #5400 to fix the reading in of colors. You would think that would be the end of it, but saving straightaway to PNG (`show()` uses the PNG format) is actually another problem again, and I think that won't be fixed until we significantly improve ImagePalette. If #5400 is merged, then the following will work. ```python from PIL import Image Image.open('UCM8.TGA').convert("RGB").show() ```
2021-06-18T23:23:56Z
8.2
python-pillow/Pillow
5,437
python-pillow__Pillow-5437
[ "5436" ]
ef9a8e5f7f7cbc28309dd5431e626ebd36ce5c9f
diff --git a/src/PIL/EpsImagePlugin.py b/src/PIL/EpsImagePlugin.py --- a/src/PIL/EpsImagePlugin.py +++ b/src/PIL/EpsImagePlugin.py @@ -354,56 +354,46 @@ def _save(im, fp, filename, eps=1): # # determine PostScript image mode if im.mode == "L": - operator = (8, 1, "image") + operator = (8, 1, b"image") elif im.mode == "RGB": - operator = (8, 3, "false 3 colorimage") + operator = (8, 3, b"false 3 colorimage") elif im.mode == "CMYK": - operator = (8, 4, "false 4 colorimage") + operator = (8, 4, b"false 4 colorimage") else: raise ValueError("image mode is not supported") - base_fp = fp - wrapped_fp = False - if fp != sys.stdout: - fp = io.TextIOWrapper(fp, encoding="latin-1") - wrapped_fp = True - - try: - if eps: - # - # write EPS header - fp.write("%!PS-Adobe-3.0 EPSF-3.0\n") - fp.write("%%Creator: PIL 0.1 EpsEncode\n") - # fp.write("%%CreationDate: %s"...) - fp.write("%%%%BoundingBox: 0 0 %d %d\n" % im.size) - fp.write("%%Pages: 1\n") - fp.write("%%EndComments\n") - fp.write("%%Page: 1 1\n") - fp.write("%%ImageData: %d %d " % im.size) - fp.write('%d %d 0 1 1 "%s"\n' % operator) - + if eps: # - # image header - fp.write("gsave\n") - fp.write("10 dict begin\n") - fp.write(f"/buf {im.size[0] * operator[1]} string def\n") - fp.write("%d %d scale\n" % im.size) - fp.write("%d %d 8\n" % im.size) # <= bits - fp.write(f"[{im.size[0]} 0 0 -{im.size[1]} 0 {im.size[1]}]\n") - fp.write("{ currentfile buf readhexstring pop } bind\n") - fp.write(operator[2] + "\n") - if hasattr(fp, "flush"): - fp.flush() - - ImageFile._save(im, base_fp, [("eps", (0, 0) + im.size, 0, None)]) - - fp.write("\n%%%%EndBinary\n") - fp.write("grestore end\n") - if hasattr(fp, "flush"): - fp.flush() - finally: - if wrapped_fp: - fp.detach() + # write EPS header + fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n") + fp.write(b"%%Creator: PIL 0.1 EpsEncode\n") + # fp.write("%%CreationDate: %s"...) + fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size) + fp.write(b"%%Pages: 1\n") + fp.write(b"%%EndComments\n") + fp.write(b"%%Page: 1 1\n") + fp.write(b"%%ImageData: %d %d " % im.size) + fp.write(b'%d %d 0 1 1 "%s"\n' % operator) + + # + # image header + fp.write(b"gsave\n") + fp.write(b"10 dict begin\n") + fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1])) + fp.write(b"%d %d scale\n" % im.size) + fp.write(b"%d %d 8\n" % im.size) # <= bits + fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1])) + fp.write(b"{ currentfile buf readhexstring pop } bind\n") + fp.write(operator[2] + b"\n") + if hasattr(fp, "flush"): + fp.flush() + + ImageFile._save(im, fp, [("eps", (0, 0) + im.size, 0, None)]) + + fp.write(b"\n%%%%EndBinary\n") + fp.write(b"grestore end\n") + if hasattr(fp, "flush"): + fp.flush() # diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2135,6 +2135,11 @@ def save(self, fp, format=None, **params): elif isinstance(fp, Path): filename = str(fp) open_fp = True + elif fp == sys.stdout: + try: + fp = sys.stdout.buffer + except AttributeError: + pass if not filename and hasattr(fp, "name") and isPath(fp.name): # only set the name for metadata purposes filename = fp.name diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py --- a/src/PIL/ImageFile.py +++ b/src/PIL/ImageFile.py @@ -493,7 +493,7 @@ def _save(im, fp, tile, bufsize=0): # But, it would need at least the image size in most cases. RawEncode is # a tricky case. bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c - if fp == sys.stdout: + if fp == sys.stdout or (hasattr(sys.stdout, "buffer") and fp == sys.stdout.buffer): fp.flush() return try: diff --git a/src/PIL/PSDraw.py b/src/PIL/PSDraw.py --- a/src/PIL/PSDraw.py +++ b/src/PIL/PSDraw.py @@ -26,39 +26,36 @@ class PSDraw: """ Sets up printing to the given file. If ``fp`` is omitted, - :py:data:`sys.stdout` is assumed. + ``sys.stdout.buffer`` or ``sys.stdout`` is assumed. """ def __init__(self, fp=None): if not fp: - fp = sys.stdout + try: + fp = sys.stdout.buffer + except AttributeError: + fp = sys.stdout self.fp = fp - def _fp_write(self, to_write): - if self.fp == sys.stdout: - self.fp.write(to_write) - else: - self.fp.write(bytes(to_write, "UTF-8")) - def begin_document(self, id=None): """Set up printing of a document. (Write PostScript DSC header.)""" # FIXME: incomplete - self._fp_write( - "%!PS-Adobe-3.0\n" - "save\n" - "/showpage { } def\n" - "%%EndComments\n" - "%%BeginDocument\n" + self.fp.write( + b"%!PS-Adobe-3.0\n" + b"save\n" + b"/showpage { } def\n" + b"%%EndComments\n" + b"%%BeginDocument\n" ) - # self._fp_write(ERROR_PS) # debugging! - self._fp_write(EDROFF_PS) - self._fp_write(VDI_PS) - self._fp_write("%%EndProlog\n") + # self.fp.write(ERROR_PS) # debugging! + self.fp.write(EDROFF_PS) + self.fp.write(VDI_PS) + self.fp.write(b"%%EndProlog\n") self.isofont = {} def end_document(self): """Ends printing. (Write PostScript DSC footer.)""" - self._fp_write("%%EndDocument\nrestore showpage\n%%End\n") + self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n") if hasattr(self.fp, "flush"): self.fp.flush() @@ -69,12 +66,13 @@ def setfont(self, font, size): :param font: A PostScript font name :param size: Size in points. """ + font = bytes(font, "UTF-8") if font not in self.isofont: # reencode font - self._fp_write(f"/PSDraw-{font} ISOLatin1Encoding /{font} E\n") + self.fp.write(b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font, font)) self.isofont[font] = 1 # rough - self._fp_write(f"/F0 {size} /PSDraw-{font} F\n") + self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font)) def line(self, xy0, xy1): """ @@ -82,7 +80,7 @@ def line(self, xy0, xy1): PostScript point coordinates (72 points per inch, (0, 0) is the lower left corner of the page). """ - self._fp_write("%d %d %d %d Vl\n" % (*xy0, *xy1)) + self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1)) def rectangle(self, box): """ @@ -97,16 +95,18 @@ def rectangle(self, box): %d %d M %d %d 0 Vr\n """ - self._fp_write("%d %d M %d %d 0 Vr\n" % box) + self.fp.write(b"%d %d M %d %d 0 Vr\n" % box) def text(self, xy, text): """ Draws text at the given position. You must use :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method. """ - text = "\\(".join(text.split("(")) - text = "\\)".join(text.split(")")) - self._fp_write(f"{xy[0]} {xy[1]} M ({text}) S\n") + text = bytes(text, "UTF-8") + text = b"\\(".join(text.split(b"(")) + text = b"\\)".join(text.split(b")")) + xy += (text,) + self.fp.write(b"%d %d M (%s) S\n" % xy) def image(self, box, im, dpi=None): """Draw a PIL image, centered in the given box.""" @@ -130,14 +130,14 @@ def image(self, box, im, dpi=None): y = ymax dx = (xmax - x) / 2 + box[0] dy = (ymax - y) / 2 + box[1] - self._fp_write(f"gsave\n{dx:f} {dy:f} translate\n") + self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy)) if (x, y) != im.size: # EpsImagePlugin._save prints the image at (0,0,xsize,ysize) sx = x / im.size[0] sy = y / im.size[1] - self._fp_write(f"{sx:f} {sy:f} scale\n") + self.fp.write(b"%f %f scale\n" % (sx, sy)) EpsImagePlugin._save(im, self.fp, None, 0) - self._fp_write("\ngrestore\n") + self.fp.write(b"\ngrestore\n") # -------------------------------------------------------------------- @@ -153,7 +153,7 @@ def image(self, box, im, dpi=None): # -EDROFF_PS = """\ +EDROFF_PS = b"""\ /S { show } bind def /P { moveto show } bind def /M { moveto } bind def @@ -182,7 +182,7 @@ def image(self, box, im, dpi=None): # Copyright (c) Fredrik Lundh 1994. # -VDI_PS = """\ +VDI_PS = b"""\ /Vm { moveto } bind def /Va { newpath arcn stroke } bind def /Vl { moveto lineto stroke } bind def @@ -207,7 +207,7 @@ def image(self, box, im, dpi=None): # 89-11-21 fl: created (pslist 1.10) # -ERROR_PS = """\ +ERROR_PS = b"""\ /landscape false def /errorBUF 200 string def /errorNL { currentpoint 10 sub exch pop 72 exch moveto } def
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -1,4 +1,5 @@ import re +import sys import zlib from io import BytesIO @@ -10,6 +11,7 @@ PillowLeakTestCase, assert_image, assert_image_equal, + assert_image_equal_tofile, hopper, is_big_endian, is_win32, @@ -711,6 +713,32 @@ def test_seek(self): with pytest.raises(EOFError): im.seek(1) + @pytest.mark.parametrize("buffer", (True, False)) + def test_save_stdout(self, buffer): + old_stdout = sys.stdout.buffer + + if buffer: + + class MyStdOut: + buffer = BytesIO() + + mystdout = MyStdOut() + else: + mystdout = BytesIO() + + sys.stdout = mystdout + + with Image.open(TEST_PNG_FILE) as im: + im.save(sys.stdout, "PNG") + + # Reset stdout + sys.stdout = old_stdout + + if buffer: + mystdout = mystdout.buffer + reloaded = Image.open(mystdout) + assert_image_equal_tofile(reloaded, TEST_PNG_FILE) + @pytest.mark.skipif(is_win32(), reason="Requires Unix or macOS") @skip_unless_feature("zlib") diff --git a/Tests/test_psdraw.py b/Tests/test_psdraw.py --- a/Tests/test_psdraw.py +++ b/Tests/test_psdraw.py @@ -1,6 +1,8 @@ import os import sys -from io import StringIO +from io import BytesIO + +import pytest from PIL import Image, PSDraw @@ -44,10 +46,21 @@ def test_draw_postscript(tmp_path): assert os.path.getsize(tempfile) > 0 -def test_stdout(): +@pytest.mark.parametrize("buffer", (True, False)) +def test_stdout(buffer): # Temporarily redirect stdout - old_stdout = sys.stdout - sys.stdout = mystdout = StringIO() + old_stdout = sys.stdout.buffer + + if buffer: + + class MyStdOut: + buffer = BytesIO() + + mystdout = MyStdOut() + else: + mystdout = BytesIO() + + sys.stdout = mystdout ps = PSDraw.PSDraw() _create_document(ps) @@ -55,4 +68,6 @@ def test_stdout(): # Reset stdout sys.stdout = old_stdout - assert mystdout.getvalue() != "" + if buffer: + mystdout = mystdout.buffer + assert mystdout.getvalue() != b""
Can't save PNG to sys.stdout <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? Just tried to run simple code (ImageDraw) ### What did you expect to happen? ### What actually happened? Exception looks very basic: ``` File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/PIL/Image.py", line 2164, in save save_handler(self, fp, filename) File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/PIL/PngImagePlugin.py", line 1225, in _save fp.write(_MAGIC) TypeError: write() argument must be str, not bytes ``` ### What are your OS, Python and Pillow versions? * OS: Android app, "pydroid3" (I don't have a computer now to check it) * Python: 3.8.3 * Pillow: 8.1.2 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> ```python import sys from PIL import Image, ImageDraw # list of dots, in the following format: [x, y, x, y, x, y,...] first = (146, 399, 163, 403, 170, 393, 169, 391, 166, 386, 170, 381, 170) #.... long tuple with Image.open("draw image.jpg") as img: draw = ImageDraw.Draw(img) for i in range(len(first)//2 - 1): draw.line(first[2*i : 2*i + 4]) # write to stdout img.save(sys.stdout, "PNG") ``` Sorry if I didn't understand the concept... This is my first issue ever...
Hi. You're free to say that Pillow should be able to work with your code, and that you'd like it to be fixed in the next Pillow release - but if you'd like an immediate solution, I'd suggest changing `sys.stdout` to `sys.stdout.buffer`. ```python import sys from PIL import Image, ImageDraw # list of dots, in the following format: [x, y, x, y, x, y,...] first = (146, 399, 163, 403, 170, 393, 169, 391, 166, 386, 170, 381, 170) #.... long tuple with Image.open("draw image.jpg") as img: draw = ImageDraw.Draw(img) for i in range(len(first)//2 - 1): draw.line(first[2*i : 2*i + 4]) # write to stdout img.save(sys.stdout.buffer, "PNG") ``` This makes a difference because while `sys.stdout` requires strings, `sys.stdout.buffer` uses bytes. ```pycon >>> import sys >>> sys.stdout.mode 'w' >>> sys.stdout.buffer.mode 'wb' ```
2021-04-25T04:40:30Z
8.2
python-pillow/Pillow
5,425
python-pillow__Pillow-5425
[ "2278" ]
ab8955b48e84b18c578d165e7d10868794311ce2
diff --git a/src/PIL/TiffTags.py b/src/PIL/TiffTags.py --- a/src/PIL/TiffTags.py +++ b/src/PIL/TiffTags.py @@ -178,7 +178,7 @@ def lookup(tag): 532: ("ReferenceBlackWhite", RATIONAL, 6), 700: ("XMP", BYTE, 0), 33432: ("Copyright", ASCII, 1), - 33723: ("IptcNaaInfo", UNDEFINED, 0), + 33723: ("IptcNaaInfo", UNDEFINED, 1), 34377: ("PhotoshopInfo", BYTE, 0), # FIXME add more tags here 34665: ("ExifIFD", LONG, 1),
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py --- a/Tests/test_file_tiff_metadata.py +++ b/Tests/test_file_tiff_metadata.py @@ -179,6 +179,12 @@ def test_no_duplicate_50741_tag(): assert TAG_IDS["BestQualityScale"] == 50780 +def test_iptc(tmp_path): + out = str(tmp_path / "temp.tiff") + with Image.open("Tests/images/hopper.Lab.tif") as im: + im.save(out) + + def test_empty_metadata(): f = io.BytesIO(b"II*\x00\x08\x00\x00\x00") head = f.read(8)
AttributeError: 'tuple' object has no attribute 'ljust' when trying to save image ### What did you do? Ran a snippet of code, see below. ### What did you expect to happen? The script to complete without error. ### What actually happened? Stack trace, see below. ### What versions of Pillow and Python are you using? Pillow==3.4.2 (also fails with Pillow==3.5.0.dev0) Python 3.5.2 Please include code that reproduces the issue and whenever possible, an image that demonstrates the issue. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as plone, django, or buildout, try to replicate the issue just using Pillow. ```python from io import BytesIO from contextlib import closing from PIL import Image image = Image.open('phototest.tif') print(image) with closing(BytesIO()) as f: image.save(f, image.format or 'JPEG') value = f.getvalue() ``` Where the image can be found [here](https://github.com/tesseract-ocr/tesseract/blob/master/testing/phototest.tif?raw=true), or download it with this command: ``` curl "https://github.com/tesseract-ocr/tesseract/blob/master/testing/phototest.tif?raw=true" > phototest.tif ``` The output is: ``` <PIL.TiffImagePlugin.TiffImageFile image mode=1 size=640x480 at 0x7F37D8546E10> Traceback (most recent call last): File "try.py", line 9, in <module> image.save(f, image.format or 'JPEG') File "/usr/local/lib/python3.5/dist-packages/PIL/Image.py", line 1698, in save save_handler(self, fp, filename) File "/usr/local/lib/python3.5/dist-packages/PIL/TiffImagePlugin.py", line 1487, in _save offset = ifd.save(fp) File "/usr/local/lib/python3.5/dist-packages/PIL/TiffImagePlugin.py", line 758, in save entries.append((tag, typ, count, data.ljust(4, b"\0"), b"")) AttributeError: 'tuple' object has no attribute 'ljust' ```
Minimal repro is: ```python from PIL import Image im = Image.open('phototest.tif') im.save('tmp.tif') ``` It's 3.x only, this works in 2.7. It succeeded before the great metadata rewrite of Pillow 3.0. Error is in a metadata entry: ``` Tag 34377, Type: 1, Value: ("8BIM\x03\xed\x00\x00\x00\x00\x00\x10\x00\xc8\x00\x00\x00\x01\x00\x01\x00\xc8\x00\x00\x00\x01\x00\x018BIM\x03\xf3\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x008BIM'\x10\x00\x00\x00\x00\x00\n\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02",) save: PhotoshopInfo (34377) - type: byte (1) - value: <table: 70 bytes> ``` and in 3.5: ``` Tag 34377, Type: 1, Value: ((b"8BIM\x03\xed\x00\x00\x00\x00\x00\x10\x00\xc8\x00\x00\x00\x01\x00\x01\x00\xc8\x00\x00\x00\x01\x00\x018BIM\x03\xf3\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x008BIM'\x10\x00\x00\x00\x00\x00\n\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02",),) save: PhotoshopInfo (34377) - type: byte (1) - value: ((b"8BIM\x03\xed\x00\x00\x00\x00\x00\x10\x00\xc8\x00\x00\x00\x01\x00\x01\x00\xc8\x00\x00\x00\x01\x00\x018BIM\x03\xf3\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x008BIM'\x10\x00\x00\x00\x00\x00\n\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02",),) ``` Any updates on this ? Was affected by this issue today (pillow 4.2.1). This is still broken for me. Pillow 7.0.0 ``` >>> im.save('/tmp/WhiteRim.tiff', compression='raw') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.6/dist-packages/PIL/Image.py", line 2102, in save save_handler(self, fp, filename) File "/usr/local/lib/python3.6/dist-packages/PIL/TiffImagePlugin.py", line 1629, in _save offset = ifd.save(fp) File "/usr/local/lib/python3.6/dist-packages/PIL/TiffImagePlugin.py", line 865, in save result = self.tobytes(offset) File "/usr/local/lib/python3.6/dist-packages/PIL/TiffImagePlugin.py", line 828, in tobytes entries.append((tag, typ, count, data.ljust(4, b"\0"), b"")) AttributeError: 'tuple' object has no attribute 'ljust' ``` I'm having this same issue with Pillow 7.0.0. But oddly the same code works fine on my Mac, but not on my AWS lambda instance. ``` Traceback (most recent call last): File "/var/task/lambda_function.py", line 121, in lambda_handler img.save(local_compressed, extension, quality=IMAGE_COMPRESSION_QUALITY) File "/var/task/PIL/Image.py", line 2102, in save save_handler(self, fp, filename) File "/var/task/PIL/TiffImagePlugin.py", line 1629, in _save offset = ifd.save(fp) File "/var/task/PIL/TiffImagePlugin.py", line 865, in save result = self.tobytes(offset) File "/var/task/PIL/TiffImagePlugin.py", line 828, in tobytes entries.append((tag, typ, count, data.ljust(4, b"\0"), b"")) AttributeError: 'tuple' object has no attribute 'ljust' 'tuple' object has no attribute 'ljust' ``` @aaronmeierx @TheJKFever What Linux version are you using? Can you reproduce it with the image from the PR [1]? If not, please can you attach your problem image? Which Python version are you using? Does it work for you with Pillow 4.3.0? How about intermediate versions? [1] https://github.com/python-pillow/Pillow/blob/master/Tests/images/issue_2278.tif I cannot reproduce with Alpine and Pillow 7.0.0 and that image: ```console wodby@php.container:/var/www/html $ cat /etc/os-release NAME="Alpine Linux" ID=alpine VERSION_ID=3.11.3 PRETTY_NAME="Alpine Linux v3.11" HOME_URL="https://alpinelinux.org/" BUG_REPORT_URL="https://bugs.alpinelinux.org/" wodby@php.container:/var/www/html $ python3 Python 3.8.1 (default, Dec 30 2019, 15:43:37) [GCC 9.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from PIL import Image >>> Image.__version__ '7.0.0' >>> im = Image.open("issue_2278.tif") >>> im <PIL.TiffImagePlugin.TiffImageFile image mode=1 size=640x480 at 0x7F9BA46C6130> >>> im.save("temp.tif") ``` For the record, the original image appears to have moved to https://github.com/tesseract-ocr/test/blob/master/testing/phototest.tif?raw=true Closing, as we don't have the images to reproduce the re-opened form of this. If they can be supplied, this can be re-opened. I'll probably submit a PR later (I think I have another issue I need to look into and if it's related, I'll roll them both together), but for now, for anyone who's stuck on this, I spent a LOT of time tracking it down today. My monkeypatch fix is: ```python from PIL.TiffImagePlugin import ImageFileDirectory_v2, TiffTags def _monkey_write_undefined(_, value): if isinstance(value, tuple) and len(value) == 1: return value[0] else: return value ImageFileDirectory_v2._write_dispatch[TiffTags.UNDEFINED] = _monkey_write_undefined ``` This is because the call to `ImageFileDirectory_v2.tobytes(…)` tries to: ```python values = value if isinstance(value, tuple) else (value,) data = self._write_dispatch[typ](self, *values) ``` When `typ=7`, this goes to `write_undefined` which returns the value; but the `data.ljust()` call below expectes a `bytes` object. It doesn't happen with the linked test image, above. I have it happening with several images that I can't share (client images), but here's some data from one of these images in case it helps: ``` ❯ nix-shell -p imagemagick --run 'identify broken.tif' broken.tif TIFF 4800x6000 4800x6000+0+0 8-bit sRGB 82.4212MiB 0.000u 0:00.005 identify: Incompatible type for "RichTIFFIPTC"; tag ignored. `TIFFFetchNormalTag' @ warning/tiff.c/TIFFWarnings/976. ❯ file broken.tif broken.tif: TIFF image data, big-endian, direntries=22, height=6000, bps=0, compression=none, PhotometricIntepretation=RGB, orientation=upper-left, width=4800 ``` Photoshop 2020 reports that this image is from `Adobe Photoshop CC 2018 (Macintosh)`. FWIW, I think this issue should be reopened, but I understand the difficulty of doing so without a test image/file. @radarhere @scoates @hugovk This issue not only still resists in latest Pillow (using 8.2.0 on Ubuntu 2.04 LTS) *but* I can provide TIFF Testdata and pytest testcases to reproduce this buggy behavior on at least 3 different (Ubuntu-)Machines. Please someone reopen this asap ... since the patch @scoates provided above finally saved my day. I think I can probably track down an image for this, now, too. Would a PR help? Personally, I'm fine with any advance. This is how I integrated and tested @scoates approach with a broken TIFF: ```python @pytest.fixture def fixture_suspicous_tif(tmp_path): img_path = tmp_path / '00000001.tif' path_tif = config('invalid_tiff_01') shutil.copy(path_tif, img_path) yield img_path def test_suspicous_tiff_01(fixture_suspicous_tif): ''' Update / sanitize TIFF header data, fails with: * Pillow 7.1.0 * Pillow 8.2.0 ''' # prevent to overwrite the script hack just for this test ImageFileDirectory_v2._write_dispatch[TiffTags.UNDEFINED] = lambda _, value: value with pytest.raises(RuntimeError) as exc: sanitize_image_headerdata(fixture_suspicous_tif) assert '\'tuple\' object has no attribute \'ljust\'' in str(exc) ``` The key issue here is, the image contains some special header tags unknown to Pillow. And there are several tags Pillow doesn't know. But we want Pillow to handle them appropriately. In my cases I face some `IPTC` header data. Even ImageMagick complains with : ``` convert-im6.q16: Incompatible type for "RichTIFFIPTC"; tag ignored. `TIFFFetchNormalTag' @ warning/tiff.c/TIFFWarnings/949. ``` even though it's not dying with the totally obfuscating `tuple object has no attribute ljust` (but throws off `IPTC` header and some `EXIF` tags as well. Please provide an example image. [00000001.zip](https://github.com/python-pillow/Pillow/files/6348348/00000001.zip) @radarhere This archive contains the file exactly as it is, without compression or whatever, utilized it for the testcase above. It's rather large, but I didn't manage to resize the image without loosing the suspicious header information. The testcase patch above tries to overwrite @scoates `_monkey_write_undefined` which I use actually to patch Pillow within my script which itself replaces ```python _write_dispatch[idx] = lambda self, *values: ( # noqa: F821 b"".join(self._pack(fmt, value) for value in values) ) ``` from current `TiffImagePlugin.py:654` in a naive fashion.
2021-04-21T12:56:12Z
8.2
python-pillow/Pillow
5,417
python-pillow__Pillow-5417
[ "5415" ]
676f4dbefb22c349c2f78f4f6aabf26e00d5efc2
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -236,15 +236,43 @@ def colorize(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoi return _lut(image, red + green + blue) +def contain(image, size, method=Image.BICUBIC): + """ + Returns a resized version of the image, set to the maximum width and height + within the requested size, while maintaining the original aspect ratio. + + :param image: The image to resize and crop. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`. + :return: An image. + """ + + im_ratio = image.width / image.height + dest_ratio = size[0] / size[1] + + if im_ratio != dest_ratio: + if im_ratio > dest_ratio: + new_height = int(image.height / image.width * size[0]) + if new_height != size[1]: + size = (size[0], new_height) + else: + new_width = int(image.width / image.height * size[1]) + if new_width != size[0]: + size = (new_width, size[1]) + return image.resize(size, resample=method) + + def pad(image, size, method=Image.BICUBIC, color=None, centering=(0.5, 0.5)): """ - Returns a sized and padded version of the image, expanded to fill the + Returns a resized and padded version of the image, expanded to fill the requested aspect ratio and size. - :param image: The image to size and crop. + :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. - :param method: What resampling method to use. Default is + :param method: Resampling method to use. Default is :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`. :param color: The background color of the padded image. :param centering: Control the position of the original image within the @@ -257,27 +285,17 @@ def pad(image, size, method=Image.BICUBIC, color=None, centering=(0.5, 0.5)): :return: An image. """ - im_ratio = image.width / image.height - dest_ratio = size[0] / size[1] - - if im_ratio == dest_ratio: - out = image.resize(size, resample=method) + resized = contain(image, size, method) + if resized.size == size: + out = resized else: out = Image.new(image.mode, size, color) - if im_ratio > dest_ratio: - new_height = int(image.height / image.width * size[0]) - if new_height != size[1]: - image = image.resize((size[0], new_height), resample=method) - - y = int((size[1] - new_height) * max(0, min(centering[1], 1))) - out.paste(image, (0, y)) + if resized.width != size[0]: + x = int((size[0] - resized.width) * max(0, min(centering[0], 1))) + out.paste(resized, (x, 0)) else: - new_width = int(image.width / image.height * size[1]) - if new_width != size[0]: - image = image.resize((new_width, size[1]), resample=method) - - x = int((size[0] - new_width) * max(0, min(centering[0], 1))) - out.paste(image, (x, 0)) + y = int((size[1] - resized.height) * max(0, min(centering[1], 1))) + out.paste(resized, (0, y)) return out @@ -304,7 +322,7 @@ def scale(image, factor, resample=Image.BICUBIC): :param image: The image to rescale. :param factor: The expansion factor, as a float. - :param resample: What resampling method to use. Default is + :param resample: Resampling method to use. Default is :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`. :returns: An :py:class:`~PIL.Image.Image` object. """ @@ -381,15 +399,15 @@ def expand(image, border=0, fill=0): def fit(image, size, method=Image.BICUBIC, bleed=0.0, centering=(0.5, 0.5)): """ - Returns a sized and cropped version of the image, cropped to the + Returns a resized and cropped version of the image, cropped to the requested aspect ratio and size. This function was contributed by Kevin Cazabon. - :param image: The image to size and crop. + :param image: The image to resize and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. - :param method: What resampling method to use. Default is + :param method: Resampling method to use. Default is :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`. :param bleed: Remove a border around the outside of the image from all four edges. The value is a decimal percentage (use 0.01 for
diff --git a/Tests/test_imageops.py b/Tests/test_imageops.py --- a/Tests/test_imageops.py +++ b/Tests/test_imageops.py @@ -37,6 +37,9 @@ def test_sanity(): ImageOps.pad(hopper("L"), (128, 128)) ImageOps.pad(hopper("RGB"), (128, 128)) + ImageOps.contain(hopper("L"), (128, 128)) + ImageOps.contain(hopper("RGB"), (128, 128)) + ImageOps.crop(hopper("L"), 1) ImageOps.crop(hopper("RGB"), 1) @@ -99,6 +102,13 @@ def test_fit_same_ratio(): assert new_im.size == (1000, 755) +@pytest.mark.parametrize("new_size", ((256, 256), (512, 256), (256, 512))) +def test_contain(new_size): + im = hopper() + new_im = ImageOps.contain(im, new_size) + assert new_im.size == (256, 256) + + def test_pad(): # Same ratio im = hopper()
Function similar to pad but returns resized image without padding I'd sure like a function that looks like ImageOps.pad https://pillow.readthedocs.io/en/stable/_modules/PIL/ImageOps.html#pad but just returns the image after resizing without adding the padding. What would be a good name for such a function? Where would it best be placed? ImageOps.fit is already taken. EDIT: Looking at #3364 `contain` seems like a decent candidate. Seems a refactor would be required. @radarhere thoughts?
2021-04-19T10:33:37Z
8.2
python-pillow/Pillow
5,330
python-pillow__Pillow-5330
[ "2202" ]
7235cf313517e03abd23f9de60e23aa392f833d6
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -1186,23 +1186,21 @@ def _save(im, fp, filename, chunk=putchunk, save_all=False): # attempt to minimize storage requirements for palette images if "bits" in im.encoderinfo: # number of bits specified by user - colors = 1 << im.encoderinfo["bits"] + colors = min(1 << im.encoderinfo["bits"], 256) else: # check palette contents if im.palette: - colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 2) + colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1) else: colors = 256 - if colors <= 2: - bits = 1 - elif colors <= 4: - bits = 2 - elif colors <= 16: - bits = 4 - else: - bits = 8 - if bits != 8: + if colors <= 16: + if colors <= 2: + bits = 1 + elif colors <= 4: + bits = 2 + else: + bits = 4 mode = f"{mode};{bits}" # encoder options @@ -1270,7 +1268,7 @@ def _save(im, fp, filename, chunk=putchunk, save_all=False): chunk(fp, cid, data) if im.mode == "P": - palette_byte_number = (2 ** bits) * 3 + palette_byte_number = colors * 3 palette_bytes = im.im.getpalette("RGB")[:palette_byte_number] while len(palette_bytes) < palette_byte_number: palette_bytes += b"\0" @@ -1281,7 +1279,7 @@ def _save(im, fp, filename, chunk=putchunk, save_all=False): if transparency or transparency == 0: if im.mode == "P": # limit to actual palette size - alpha_bytes = 2 ** bits + alpha_bytes = colors if isinstance(transparency, bytes): chunk(fp, b"tRNS", transparency[:alpha_bytes]) else: @@ -1302,7 +1300,7 @@ def _save(im, fp, filename, chunk=putchunk, save_all=False): else: if im.mode == "P" and im.im.getpalettemode() == "RGBA": alpha = im.im.getpalette("RGBA", "A") - alpha_bytes = 2 ** bits + alpha_bytes = colors chunk(fp, b"tRNS", alpha[:alpha_bytes]) dpi = im.encoderinfo.get("dpi")
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -634,6 +634,16 @@ def test_specify_bits(self, tmp_path): with Image.open(out) as reloaded: assert len(reloaded.png.im_palette[1]) == 48 + def test_plte_length(self, tmp_path): + im = Image.new("P", (1, 1)) + im.putpalette((1, 1, 1)) + + out = str(tmp_path / "temp.png") + im.save(str(tmp_path / "temp.png")) + + with Image.open(out) as reloaded: + assert len(reloaded.png.im_palette[1]) == 3 + def test_exif(self): # With an EXIF chunk with Image.open("Tests/images/exif.png") as im:
PNG: unnecessary padding in PLTE _Pillow_ incorrectly enforces a minimum of `2` palette entries. ```Python from PIL import Image img = Image.new(size = (1, 1), mode = 'P') img.putpalette((1, 1, 1)) img.save('file.png') ``` ```Bash $ pngcheck -v file.png ... 1 x 1 image, 1-bit palette, non-interlaced chunk PLTE at offset 0x00025, length 6: 2 palette entries ... ``` And pads the palette to `bit ** 2` entries. ```Python from PIL import Image img = Image.new(size = (3, 3), mode = 'P') img.putpalette((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5)) # 5 img.save('file.png') ``` ```Bash $ pngcheck -v file.png ... 3 x 3 image, 4-bit palette, non-interlaced chunk PLTE at offset 0x00025, length 48: 16 palette entries ... ``` It's [neither required nor recommended](https://www.w3.org/TR/PNG/#11PLTE). > It is permissible to have fewer entries than the bit depth would allow.
```diff diff --git a/PIL/PngImagePlugin.py b/PIL/PngImagePlugin.py index 5e5eb14..9f883c9 100644 --- a/PIL/PngImagePlugin.py +++ b/PIL/PngImagePlugin.py @@ -671,7 +671,7 @@ def _save(im, fp, filename, chunk=putchunk, check=0): else: # check palette contents if im.palette: - colors = max(min(len(im.palette.getdata()[1])//3, 256), 2) + colors = max(min(len(im.palette.getdata()[1])//3, 256), 1) else: colors = 256 @@ -740,7 +740,7 @@ def _save(im, fp, filename, chunk=putchunk, check=0): chunk(fp, cid, data) if im.mode == "P": - palette_byte_number = (2 ** bits) * 3 + palette_byte_number = min(2 ** bits, colors) * 3 palette_bytes = im.im.getpalette("RGB")[:palette_byte_number] while len(palette_bytes) < palette_byte_number: palette_bytes += b'\0' @@ -752,7 +752,7 @@ def _save(im, fp, filename, chunk=putchunk, check=0): if transparency or transparency == 0: if im.mode == "P": # limit to actual palette size - alpha_bytes = 2**bits + alpha_bytes = min(2**bits, colors) if isinstance(transparency, bytes): chunk(fp, b"tRNS", transparency[:alpha_bytes]) else: @@ -773,7 +773,7 @@ def _save(im, fp, filename, chunk=putchunk, check=0): else: if im.mode == "P" and im.im.getpalettemode() == "RGBA": alpha = im.im.getpalette("RGBA", "A") - alpha_bytes = 2**bits + alpha_bytes = min(2**bits, colors) chunk(fp, b"tRNS", alpha[:alpha_bytes]) dpi = im.encoderinfo.get("dpi") ``` Works, but it's not tested extensively. ```Python img = Image.frombytes('P', (1, 1), '\x00') img.putpalette('\xFF\x00\x00') # R img.save('file.png') # chunk PLTE at offset 0x00025, length 3: 1 palette entry img = Image.frombytes('P', (3, 3), '\x00' * 3 + '\x01' * 3 + '\x02' * 3) img.putpalette('\xFF\x00\x00' '\x00\xFF\x00' '\x00\x00\xFF') # RGB img.save('file.png') # chunk PLTE at offset 0x00025, length 9: 3 palette entries img.save('file.png', transparency = 0) # chunk PLTE at offset 0x00025, length 9: 3 palette entries # chunk tRNS at offset 0x0003a, length 1: 1 transparency entry img.save('file.png', transparency = '\x00\x80\xFF') # chunk PLTE at offset 0x00025, length 9: 3 palette entries # chunk tRNS at offset 0x0003a, length 3: 3 transparency entries ``` Just a note - the minimum of 2 was added in https://github.com/python-pillow/Pillow/pull/537/commits/6457eed2cbedfd785df8579933d0ced0f6729df2 I've created #5330 to resolve this.
2021-03-15T09:32:07Z
8.1
python-pillow/Pillow
5,313
python-pillow__Pillow-5313
[ "5298" ]
d9e4424a7fa6e6e0cd91fd5da89f0a5ccc00f7b8
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1544,8 +1544,6 @@ def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") - if min(dest) < 0: - raise ValueError("Destination must be non-negative") if len(source) == 2: source = source + im.size
diff --git a/Tests/test_image.py b/Tests/test_image.py --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -344,6 +344,12 @@ def test_alpha_inplace(self): assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63))) assert offset.size == (128, 128) + # with negative offset + offset = src.copy() + offset.alpha_composite(over, (-64, -64)) + assert_image_equal(offset.crop((0, 0, 63, 63)), target.crop((64, 64, 127, 127))) + assert offset.size == (128, 128) + # offset and crop box = src.copy() box.alpha_composite(over, (64, 64), (0, 0, 32, 32)) @@ -367,8 +373,6 @@ def test_alpha_inplace(self): source.alpha_composite(over, 0) with pytest.raises(ValueError): source.alpha_composite(over, (0, 0), 0) - with pytest.raises(ValueError): - source.alpha_composite(over, (0, -1)) with pytest.raises(ValueError): source.alpha_composite(over, (0, 0), (0, -1))
alpha_composite should be like paste and allow negative destinations If you try to use `alpha_composite` with a negative dest, it produces an error message. For example: ```python from PIL import Image solid_green = Image.new("RGBA",(100,100),(0,255,0,255)) semidark = Image.new("RGBA",(100,100),(0,0,0,127)) ac_result = solid_green.copy() ac_result.alpha_composite(semidark,(-50,50)) ac_result.show() # => ValueError: Destination must be non-negative ``` Contrast this with `paste,` which allows negative destinations: ```python from PIL import Image solid_green = Image.new("RGBA",(100,100),(0,255,0,255)) semidark = Image.new("RGBA",(100,100),(0,0,0,127)) paste_result = solid_green.copy() paste_result.paste(semidark,(-50,50),semidark) paste_result.show() # Works but colors aren't alpha composited ``` Negatives do indicate clipping on the left or top but note that `alpha_composite` (like `paste`) already allows clipping on the right and bottom. ```python from PIL import Image solid_green = Image.new("RGBA",(100,100),(0,255,0,255)) semidark = Image.new("RGBA",(100,100),(0,0,0,127)) ac_result = solid_green.copy() ac_result.alpha_composite(semidark,(50,50)) ac_result.show() # Works great! ``` Until this issue is addressed, here is a work around: ```python def alpha_composite_workaround(image0, image1, dest): x1,y1 = dest if x1 >= 0 and y1 >= 0: image0.alpha_composite(image1, dest=(x1, y1)) else: temp = Image.new("RGBA", image0.size, (0, 0, 0, 0)) temp.paste(image1, (x1, y1)) image0.alpha_composite(temp) from PIL import Image solid_green = Image.new("RGBA",(100,100),(0,255,0,255)) semidark = Image.new("RGBA",(100,100),(0,0,0,127)) ac_result = solid_green.copy() alpha_composite_workaround(ac_result,semidark,(-50,50)) ac_result.show() ```
`alpha_composite` was added in #2595 by @wiredfool. Did he have any thoughts on this?
2021-03-06T10:02:40Z
8.1
python-pillow/Pillow
5,208
python-pillow__Pillow-5208
[ "4765" ]
441a1cf9cf7a6fa018e7cecdfbd70b5680b53f26
diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -257,6 +257,96 @@ def rectangle(self, xy, fill=None, outline=None, width=1): if ink is not None and ink != fill and width != 0: self.draw.draw_rectangle(xy, ink, 0, width) + def rounded_rectangle(self, xy, radius=0, fill=None, outline=None, width=1): + """Draw a rounded rectangle.""" + if isinstance(xy[0], (list, tuple)): + (x0, y0), (x1, y1) = xy + else: + x0, y0, x1, y1 = xy + + d = radius * 2 + + full_x = d >= x1 - x0 + if full_x: + # The two left and two right corners are joined + d = x1 - x0 + full_y = d >= y1 - y0 + if full_y: + # The two top and two bottom corners are joined + d = y1 - y0 + if full_x and full_y: + # If all corners are joined, that is a circle + return self.ellipse(xy, fill, outline, width) + + if d == 0: + # If the corners have no curve, that is a rectangle + return self.rectangle(xy, fill, outline, width) + + ink, fill = self._getink(outline, fill) + + def draw_corners(pieslice): + if full_x: + # Draw top and bottom halves + parts = ( + ((x0, y0, x0 + d, y0 + d), 180, 360), + ((x0, y1 - d, x0 + d, y1), 0, 180), + ) + elif full_y: + # Draw left and right halves + parts = ( + ((x0, y0, x0 + d, y0 + d), 90, 270), + ((x1 - d, y0, x1, y0 + d), 270, 90), + ) + else: + # Draw four separate corners + parts = ( + ((x1 - d, y0, x1, y0 + d), 270, 360), + ((x1 - d, y1 - d, x1, y1), 0, 90), + ((x0, y1 - d, x0 + d, y1), 90, 180), + ((x0, y0, x0 + d, y0 + d), 180, 270), + ) + for part in parts: + if pieslice: + self.draw.draw_pieslice(*(part + (fill, 1))) + else: + self.draw.draw_arc(*(part + (ink, width))) + + if fill is not None: + draw_corners(True) + + if full_x: + self.draw.draw_rectangle( + (x0, y0 + d / 2 + 1, x1, y1 - d / 2 - 1), fill, 1 + ) + else: + self.draw.draw_rectangle( + (x0 + d / 2 + 1, y0, x1 - d / 2 - 1, y1), fill, 1 + ) + if not full_x and not full_y: + self.draw.draw_rectangle( + (x0, y0 + d / 2 + 1, x0 + d / 2, y1 - d / 2 - 1), fill, 1 + ) + self.draw.draw_rectangle( + (x1 - d / 2, y0 + d / 2 + 1, x1, y1 - d / 2 - 1), fill, 1 + ) + if ink is not None and ink != fill and width != 0: + draw_corners(False) + + if not full_x: + self.draw.draw_rectangle( + (x0 + d / 2 + 1, y0, x1 - d / 2 - 1, y0 + width - 1), ink, 1 + ) + self.draw.draw_rectangle( + (x0 + d / 2 + 1, y1 - width + 1, x1 - d / 2 - 1, y1), ink, 1 + ) + if not full_y: + self.draw.draw_rectangle( + (x0, y0 + d / 2 + 1, x0 + width - 1, y1 - d / 2 - 1), ink, 1 + ) + self.draw.draw_rectangle( + (x1 - width + 1, y0 + d / 2 + 1, x1, y1 - d / 2 - 1), ink, 1 + ) + def _multiline_check(self, text): """Draw text.""" split_character = "\n" if isinstance(text, str) else b"\n"
diff --git a/Tests/images/imagedraw_rounded_rectangle.png b/Tests/images/imagedraw_rounded_rectangle.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_both.png b/Tests/images/imagedraw_rounded_rectangle_both.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_both.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_x.png b/Tests/images/imagedraw_rounded_rectangle_x.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_x.png differ diff --git a/Tests/images/imagedraw_rounded_rectangle_y.png b/Tests/images/imagedraw_rounded_rectangle_y.png new file mode 100644 Binary files /dev/null and b/Tests/images/imagedraw_rounded_rectangle_y.png differ diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -706,6 +706,58 @@ def test_rectangle_translucent_outline(): ) +@pytest.mark.parametrize( + "xy", + [(10, 20, 190, 180), ([10, 20], [190, 180]), ((10, 20), (190, 180))], +) +def test_rounded_rectangle(xy): + # Arrange + im = Image.new("RGB", (200, 200)) + draw = ImageDraw.Draw(im) + + # Act + draw.rounded_rectangle(xy, 30, fill="red", outline="green", width=5) + + # Assert + assert_image_equal_tofile(im, "Tests/images/imagedraw_rounded_rectangle.png") + + +def test_rounded_rectangle_zero_radius(): + # Arrange + im = Image.new("RGB", (W, H)) + draw = ImageDraw.Draw(im) + + # Act + draw.rounded_rectangle(BBOX1, 0, fill="blue", outline="green", width=5) + + # Assert + assert_image_equal_tofile(im, "Tests/images/imagedraw_rectangle_width_fill.png") + + +@pytest.mark.parametrize( + "xy, suffix", + [ + ((20, 10, 80, 90), "x"), + ((10, 20, 90, 80), "y"), + ((20, 20, 80, 80), "both"), + ], +) +def test_rounded_rectangle_translucent(xy, suffix): + # Arrange + im = Image.new("RGB", (W, H)) + draw = ImageDraw.Draw(im, "RGBA") + + # Act + draw.rounded_rectangle( + xy, 30, fill=(255, 0, 0, 127), outline=(0, 255, 0, 127), width=5 + ) + + # Assert + assert_image_equal_tofile( + im, "Tests/images/imagedraw_rounded_rectangle_" + suffix + ".png" + ) + + def test_floodfill(): red = ImageColor.getrgb("red")
Function for Rounded Rectangle ### Feature Request I got a feature request for the `ImageDraw` module. For more modern design, it's very useful to create a rectangle with rounded corners. Currently, it requires a higher effort to create such a rounded rectangle. My Code: ```py def create_rounded_rectangle_mask(size, radius, alpha=255): factor = 5 # Factor to increase the image size that I can later antialiaze the corners radius = radius * factor image = Image.new('RGBA', (size[0] * factor, size[1] * factor), (0, 0, 0, 0)) # create corner corner = Image.new('RGBA', (radius, radius), (0, 0, 0, 0)) draw = ImageDraw.Draw(corner) # added the fill = .. you only drew a line, no fill draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=(50, 50, 50, alpha + 55)) # max_x, max_y mx, my = (size[0] * factor, size[1] * factor) # paste corner rotated as needed # use corners alpha channel as mask image.paste(corner, (0, 0), corner) image.paste(corner.rotate(90), (0, my - radius), corner.rotate(90)) image.paste(corner.rotate(180), (mx - radius, my - radius), corner.rotate(180)) image.paste(corner.rotate(270), (mx - radius, 0), corner.rotate(270)) # draw both inner rects draw = ImageDraw.Draw(image) draw.rectangle([(radius, 0), (mx - radius, my)], fill=(50, 50, 50, alpha)) draw.rectangle([(0, radius), (mx, my - radius)], fill=(50, 50, 50, alpha)) image = image.resize(size, Image.ANTIALIAS) # Smooth the corners return image ``` This mask will be used to paste with a normal rectangle.
So to be clear, you can already achieve the desired outcome with Pillow, you're just suggesting that this code become a part of Pillow? Yeah I think there will be several ppl. which might use such function. I also found those functions in other image libraries (other languages) so might be worth considering to implement. My implementation also won't be the best, so you or other ppl. find ways to improve it. I don't understand what you were trying to achieve with the `alpha` argument. Using your code, 255 is normal. ```python create_rounded_rectangle_mask((200, 100), 30, 255).show() ``` ![255](https://user-images.githubusercontent.com/3112309/104695586-1cb4fe80-5761-11eb-9500-147106e0a17a.png) But 127 and 0 just don't seem like they would be helpful. ```python create_rounded_rectangle_mask((200, 100), 30, 127).show() ``` ![127](https://user-images.githubusercontent.com/3112309/104695623-28082a00-5761-11eb-952d-a713ae2b1494.png) ```python create_rounded_rectangle_mask((200, 100), 30, 0).show() ``` ![0](https://user-images.githubusercontent.com/3112309/104695626-29d1ed80-5761-11eb-85e1-e13da3193819.png) I've created PR #5208. See what you think > I don't understand what you were trying to achieve with the `alpha` argument. > Using your code, 255 is normal. @radarhere Am not fully aware of how to use this value right. I encountered an issue if I create a rounded rectangle with alpha lower than 255. Eg. I created a translucent bar background with Alpha set to 30: ![DiscordPTB_kGBwbpMnIK](https://user-images.githubusercontent.com/24532065/104728497-3f322200-5737-11eb-9c8b-f893852dd63a.png) This happens when you not adjusting alpha: ![DiscordPTB_i9mppapcT4](https://user-images.githubusercontent.com/24532065/104728814-c2ec0e80-5737-11eb-9f99-14d3ca0bb3c3.png) My version of just using the same alpha as the image is imperfect too. If you zoom in, you'll see that the corners got a different alpha. Ok, sure. Using my PR, you should be able to just set `fill` to a color with an alpha value. ```python from PIL import Image, ImageDraw im = Image.new("RGB", (500, 100), (0, 0, 100)) draw = ImageDraw.Draw(im, "RGBA") draw.rounded_rectangle((20, 20, 480, 80), 30, fill=(255,255,255,50)) draw.rounded_rectangle((20, 20, 280, 80), 30, fill=(255,0,0,100)) im.show() ``` ![out](https://user-images.githubusercontent.com/3112309/104810029-22d0db00-5846-11eb-83e2-098ed96758b0.png) @radarhere Sounds great! Looking forward to use this function in a future version. But I think it might be helpful to either implement corner smoothing or provide help how to do it in docs. Your idea of using antialiasing to create a smoother result doesn't purely apply to rounded rectangles - it might equally be applied to other shapes. While I acknowledge that it might be useful, I'm reluctant to officially endorse it as a strategy - if there is a need for it, my personal feeling is that it is more of a workaround than a proper solution. Feel free to create a PR yourself, or if you'd like to continue talking about smoothing, would you be able to open a new issue? It would be nice to keep this issue specifically about rounded rectangles.
2021-01-15T11:48:12Z
8.1
python-pillow/Pillow
5,139
python-pillow__Pillow-5139
[ "5116" ]
b48cfa747cecd02ee4d76d12f7bbf64e186982af
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -670,7 +670,10 @@ def _repr_png_(self): :returns: png version of the image as bytes """ b = io.BytesIO() - self.save(b, "PNG") + try: + self.save(b, "PNG") + except Exception as e: + raise ValueError("Could not save to PNG for display") from e return b.getvalue() @property
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -537,6 +537,12 @@ def test_repr_png(self): assert repr_png.format == "PNG" assert_image_equal(im, repr_png) + def test_repr_png_error(self): + im = hopper("F") + + with pytest.raises(ValueError): + im._repr_png_() + def test_chunk_order(self, tmp_path): with Image.open("Tests/images/icc_profile.png") as im: test_file = str(tmp_path / "temp.png")
Unclear error when displaying images from arrays of float dtype in notebook Floating point images from numpy arrays via the `PIL.Image.fromarray()` raise an unclear error when accidentally returned in jupyter notebook as the final line in a cell. This triggers `IPython.display.display()` on the image object, which in turn calls the image object `_repr_png_()` method, which raises the error below. ### What did you do? Called ```python import numpy as np from PIL.Image import fromarray fromarray(np.random.random((30, 30))) ``` ### What did you expect to happen? Either: A) Attempt to show the image given some defaults (like showing the image on a 8bit depth (resulting in a black image or very dark image) B) More likely: Raise a clear error saying that you can't create images out of floating point values, and should instead (probably rescale to an appropriate bitdepth range and) change the dtype to be `uint8` or some other accepted dtype. ### What actually happened? I get an error about how one cannot write mode F as png: ```python --------------------------------------------------------------------------- KeyError Traceback (most recent call last) ~\Miniconda3\envs\py\lib\site-packages\PIL\PngImagePlugin.py in _save(im, fp, filename, chunk, save_all) 1219 try: -> 1220 rawmode, mode = _OUTMODES[mode] 1221 except KeyError as e: KeyError: 'F' The above exception was the direct cause of the following exception: OSError Traceback (most recent call last) ~\Miniconda3\envs\py\lib\site-packages\IPython\core\formatters.py in __call__(self, obj) 343 method = get_real_method(obj, self.print_method) 344 if method is not None: --> 345 return method() 346 return None 347 else: ~\Miniconda3\envs\py\lib\site-packages\PIL\Image.py in _repr_png_(self) 671 """ 672 b = io.BytesIO() --> 673 self.save(b, "PNG") 674 return b.getvalue() 675 ~\Miniconda3\envs\py\lib\site-packages\PIL\Image.py in save(self, fp, format, **params) 2149 2150 try: -> 2151 save_handler(self, fp, filename) 2152 finally: 2153 # do what we can to clean up ~\Miniconda3\envs\py\lib\site-packages\PIL\PngImagePlugin.py in _save(im, fp, filename, chunk, save_all) 1220 rawmode, mode = _OUTMODES[mode] 1221 except KeyError as e: -> 1222 raise OSError(f"cannot write mode {mode} as PNG") from e 1223 1224 # OSError: cannot write mode F as PNG ``` ### What are your OS, Python and Pillow versions? * OS: Win 10 * Python: 3.9 * Pillow: 8.0.1 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. -->
For A, you may be interested in #2663 and the suggested PR #3172. The idea is that you could append `convert_mode=True` and it would then convert automatically if saving wasn't possible.
2020-12-27T04:49:50Z
8
python-pillow/Pillow
5,125
python-pillow__Pillow-5125
[ "3153" ]
ce3d80e7136710ea81b206fd160484013f913c2e
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -301,13 +301,14 @@ def load_end(self): # if the disposal method is 'do not dispose', transparent # pixels should show the content of the previous frame - if self._prev_im and self.disposal_method == 1: + if self._prev_im and self._prev_disposal_method == 1: # we do this by pasting the updated area onto the previous # frame which we then use as the current image content updated = self._crop(self.im, self.dispose_extent) self._prev_im.paste(updated, self.dispose_extent, updated.convert("RGBA")) self.im = self._prev_im self._prev_im = self.im.copy() + self._prev_disposal_method = self.disposal_method def _close__fp(self): try:
diff --git a/Tests/images/dispose_none_load_end.gif b/Tests/images/dispose_none_load_end.gif new file mode 100644 Binary files /dev/null and b/Tests/images/dispose_none_load_end.gif differ diff --git a/Tests/images/dispose_none_load_end_second.gif b/Tests/images/dispose_none_load_end_second.gif new file mode 100644 Binary files /dev/null and b/Tests/images/dispose_none_load_end_second.gif differ diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -307,6 +307,20 @@ def test_dispose_none(): pass +def test_dispose_none_load_end(): + # Test image created with: + # + # im = Image.open("transparent.gif") + # im_rotated = im.rotate(180) + # im.save("dispose_none_load_end.gif", + # save_all=True, append_images=[im_rotated], disposal=[1,2]) + with Image.open("Tests/images/dispose_none_load_end.gif") as img: + img.seek(1) + + with Image.open("Tests/images/dispose_none_load_end_second.gif") as expected: + assert_image_equal(img, expected) + + def test_dispose_background(): with Image.open("Tests/images/dispose_bgnd.gif") as img: try:
Last frame of gif has second last frame merged to it ### What did you do? I iterated through gif frames and added copies of the frames converted to rgba to a list of the following 4 frame gif ![gif](https://raw.githubusercontent.com/s0hvaperuna/pillow-images/master/eevee.gif "gif") This was the code I used and what produced the invalid result ```py frames = [] while True: frames.append(im.copy().convert('RGBA')) try: im.seek(im.tell() + 1) except EOFError: break ``` ### What did you expect to happen? Expected that all the frames would look normal without them merging ### What actually happened? The last 2 images merged ![Invalid frame](https://raw.githubusercontent.com/s0hvaperuna/pillow-images/master/frame_3_invalid.png "Invalid frame") as in the following pic when the expected result would be ![Correct frame](https://raw.githubusercontent.com/s0hvaperuna/pillow-images/master/frame_3_correct.png "Correct frame") The second last frame was kept normal but the last frame included the second last frame merged to it I was able to get the desired result by using the following modification of my original loop ```py frames = [] while True: frames.append(im.copy().convert('RGBA')) try: im.seek(im.tell() + 1) except EOFError: frames[-1] = im.copy().convert('RGBA') break ``` ### What versions of Pillow and Python are you using? Python 3.6.4 Pillow 5.1.0
GIFs have a value called a 'disposal method'. For the last frame in this image, it is set to 'Do not dispose. The graphic is to be left in place.' So from what I can see, Pillow is behaving correctly. Clearly standard image viewers have other ideas about what to do in this situation though, and I don't know what logic they are using. This is resolved by #3434. I'm also going to move discussion of https://github.com/python-pillow/Pillow/issues/3665#issuecomment-471973989 here, which looks like the same problem, and is also solved by #3434. > ```python > import requests > from PIL import Image > response = requests.get('https://66.media.tumblr.com/tumblr_lzkp40b0Sl1qhwcy0.gif') > im = Image.open(BytesIO(response.content)) > im.save('1.png', 'PNG') > im.seek(1) > im.load() > im.save('2.png', 'PNG') > ``` > The `2.png` has second frame pasted onto first. > Expected result is second frame pasted into background (transparent).
2020-12-23T02:24:34Z
8
python-pillow/Pillow
4,966
python-pillow__Pillow-4966
[ "4939" ]
15c339470d8e0d04370146fecc82038cfc419fa0
diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -162,10 +162,6 @@ def _bitmap(self, header=0, offset=0): else (1 << file_info["bits"]) ) - # ------------------------------- Check abnormal values for DOS attacks - if file_info["width"] * file_info["height"] > 2 ** 31: - raise OSError("Unsupported BMP Size: (%dx%d)" % self.size) - # ---------------------- Check bit depth for unusual unsupported values self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None)) if self.mode is None:
diff --git a/Tests/test_decompression_bomb.py b/Tests/test_decompression_bomb.py --- a/Tests/test_decompression_bomb.py +++ b/Tests/test_decompression_bomb.py @@ -60,6 +60,10 @@ def test_exception_gif(self): with pytest.raises(Image.DecompressionBombError): Image.open("Tests/images/decompression_bomb.gif") + def test_exception_bmp(self): + with pytest.raises(Image.DecompressionBombError): + Image.open("Tests/images/bmp/b/reallybig.bmp") + class TestDecompressionCrop: @classmethod
[Feature Request] Making BMP pixel size limit configurable Hello, I have been a happy user of Pillow for a long time, but new to the developer community. Thank you for making such amazing work available to the world. I am writing to ask if **the community would be open to the idea of making the hard-coded BMP [file size limit](https://github.com/python-pillow/Pillow/blob/5ce2fac3d6cfcf9af0f84502d9bd0c2dfcfcb398/src/PIL/BmpImagePlugin.py#L166) configurable by clients**. I need to work with large bmp files whose pixel counts exceed the limit, which does not appear configurable by design. Therefore, when I try opening the large bmp files using PIL, I get `OSError: Unsupported BMP Size`. It appears I need to modify the source code to lift the hard-coded limit. I understand, as documented, the motivation is to mitigate the risk with DOS attacks. However, I suppose there might be clients, just like me, that use PIL in an environment where there's a relatively limited DOS risk and are willing to accept the risk in any case. If the idea makes sense, I'd love to work on a PR. Look forward to your advice and thoughts. FYI: the relevant code. ![image](https://user-images.githubusercontent.com/3280262/94590121-2c4b2d00-02c1-11eb-9596-96eed378d6b5.png) source: https://github.com/python-pillow/Pillow/blob/5ce2fac3d6cfcf9af0f84502d9bd0c2dfcfcb398/src/PIL/BmpImagePlugin.py#L166
Makes sense to me. `MAX_IMAGE_PIXELS * 2` is smaller than `2 ** 31`, so it's not like we would be loosening the restriction either. What would be the action here, removing the check altogether, or making it configurable? I would think the best way forward is to make it configurable, by replacing the check for a size of `2 ** 31` with the more standard `_decompression_bomb_check`. Users could effectively configure it then by setting `Image.MAX_IMAGE_PIXELS`. Thank you for sharing your advice about `_decompression_bomb_check`. Since the check is a function of `Image.MAX_IMAGE_PIXELS` that is already configurable, I think it sounds like a clean, natural solution. I think a path forward seems clear for us (@alicanb and I work together). We will send a PR soon.
2020-10-12T08:37:08Z
7.2
python-pillow/Pillow
4,677
python-pillow__Pillow-4677
[ "4676" ]
9df95e77c58566dff411b61f44298ebbbeb9efae
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -3289,7 +3289,9 @@ def load(self, data): if not data: return - self.fp = io.BytesIO(data[6:]) + if data.startswith(b"Exif\x00\x00"): + data = data[6:] + self.fp = io.BytesIO(data) self.head = self.fp.read(8) # process dictionary from . import TiffImagePlugin
diff --git a/Tests/test_file_webp_metadata.py b/Tests/test_file_webp_metadata.py --- a/Tests/test_file_webp_metadata.py +++ b/Tests/test_file_webp_metadata.py @@ -30,6 +30,15 @@ def test_read_exif_metadata(): assert exif_data == expected_exif +def test_read_exif_metadata_without_prefix(): + with Image.open("Tests/images/flower2.webp") as im: + # Assert prefix is not present + assert im.info["exif"][:6] != b"Exif\x00\x00" + + exif = im.getexif() + assert exif[305] == "Adobe Photoshop CS6 (Macintosh)" + + def test_write_exif_metadata(): file_path = "Tests/images/flower.jpg" test_buffer = BytesIO()
getexif() crashes when reading empty EXIF data from a PNG file saved by RawTherapy 5.8 ### What did you do? Converted a RAW file to PNG using RawTherapy 5.8. Opened the image file with Pillow and called getexif() ### What did you expect to happen? Since the file has no EXIF data, the expected output is None or an empty dictionary. `pyexiv2` returns an empty dictionary. ### What actually happened? ``` Traceback (most recent call last): File "/home/roman/Projects/pillow-png-getexif/read_png_exif.py", line 8, in <module> exif = img.getexif() File "/home/roman/Projects/mikula/venv/lib/python3.8/site-packages/PIL/PngImagePlugin.py", line 951, in getexif self._exif.load(exif_info) File "/home/roman/Projects/mikula/venv/lib/python3.8/site-packages/PIL/Image.py", line 3271, in load self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head) File "/home/roman/Projects/mikula/venv/lib/python3.8/site-packages/PIL/TiffImagePlugin.py", line 900, in __init__ super().__init__(*args, **kwargs) File "/home/roman/Projects/mikula/venv/lib/python3.8/site-packages/PIL/TiffImagePlugin.py", line 466, in __init__ raise SyntaxError("not a TIFF file (header %r not valid)" % ifh) SyntaxError: not a TIFF file (header b'\x00\x00\x11\x00\x00\x01\x04\x00' not valid) ``` ### What are your OS, Python and Pillow versions? * OS: Ubuntu 20.04 * Python: Python version 3.8.2 [GCC 9.3.0] * Pillow: 7.1.1 ```python fn = "mug_small.png" img = Image.open(fn) exif = img.getexif() ``` The code and the test image are available on [github](https://github.com/RomanKosobrodov/pillow-png-getexif).
The file actually does have EXIF data. It may not have an eXIf chunk, but it has a zTXt chunk, "Raw profile type exif". See https://exiftool.org/TagNames/PNG.html#TextualData for some more information. Pillow has an assumption that EXIF data starts with "Exif\x00\x00", but that is not the case for your image. Here is some code as a demonstration. ```python from PIL import Image img = Image.open("mug_small.png") if "Raw profile type exif" in img.info: rawProfileTypeExif = bytes.fromhex( "".join(img.info["Raw profile type exif"].split("\n")[3:]) ) if rawProfileTypeExif[:6] != "Exif\x00\x00": print("Fix missing EXIF prefix") img.info["exif"] = b"Exif\x00\x00"+rawProfileTypeExif exif = img.getexif() print(exif) ```
2020-06-07T10:06:37Z
7.1
python-pillow/Pillow
4,749
python-pillow__Pillow-4749
[ "4731" ]
cc83723d6b1277c9b7b782839d4b5d20cadf88c9
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -70,7 +70,9 @@ def autocontrast(image, cutoff=0, ignore=None): becomes white (255). :param image: The image to process. - :param cutoff: How many percent to cut off from the histogram. + :param cutoff: The percent to cut off from the histogram on the low and + high ends. Either a tuple of (low, high), or a single + number for both. :param ignore: The background pixel value (use None for no background). :return: An image. """ @@ -88,12 +90,14 @@ def autocontrast(image, cutoff=0, ignore=None): h[ix] = 0 if cutoff: # cut off pixels from both ends of the histogram + if not isinstance(cutoff, tuple): + cutoff = (cutoff, cutoff) # get number of pixels n = 0 for ix in range(256): n = n + h[ix] # remove cutoff% pixels from the low end - cut = n * cutoff // 100 + cut = n * cutoff[0] // 100 for lo in range(256): if cut > h[lo]: cut = cut - h[lo] @@ -103,8 +107,8 @@ def autocontrast(image, cutoff=0, ignore=None): cut = 0 if cut <= 0: break - # remove cutoff% samples from the hi end - cut = n * cutoff // 100 + # remove cutoff% samples from the high end + cut = n * cutoff[1] // 100 for hi in range(255, -1, -1): if cut > h[hi]: cut = cut - h[hi]
diff --git a/Tests/test_imageops.py b/Tests/test_imageops.py --- a/Tests/test_imageops.py +++ b/Tests/test_imageops.py @@ -300,3 +300,14 @@ def check(orientation_im): "Tests/images/hopper_orientation_" + str(i) + ext ) as orientation_im: check(orientation_im) + + +def test_autocontrast_cutoff(): + # Test the cutoff argument of autocontrast + with Image.open("Tests/images/bw_gradient.png") as img: + + def autocontrast(cutoff): + return ImageOps.autocontrast(img, cutoff).histogram() + + assert autocontrast(10) == autocontrast((10, 10)) + assert autocontrast(10) != autocontrast((1, 10))
Autocontrast cutoff improvement <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? I am trying to improve image contrast. ### What did you expect to happen? I expect to be able to control the cutoff values for each side of the histograms. ### What actually happened? The cutoff value of PIL.ImageOps.autocontrast() cutoff the histogram from both side. What should happen is the user should be given the custom control to specify the percentage cutoff of both the right and the left side separately ### What are your OS, Python and Pillow versions? * OS: Windows 10 * Python: Python 3.8.2 * Pillow: PIL 7.1.2 <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> ```python from PIL import Image, ImageOps img = Image.open("ky.jpg").convert("L") edited = ImageOps.autocontrast(img, cutoff=4 edited.save("pil_1.jpg") ```
2020-06-30T20:48:44Z
7.2
python-pillow/Pillow
4,741
python-pillow__Pillow-4741
[ "4732" ]
977094d4b5554dc575264800e787472d9343e390
diff --git a/src/PIL/IcnsImagePlugin.py b/src/PIL/IcnsImagePlugin.py --- a/src/PIL/IcnsImagePlugin.py +++ b/src/PIL/IcnsImagePlugin.py @@ -337,6 +337,10 @@ def _save(im, fp, filename): # iconutil -c icns -o {} {} + fp_only = not filename + if fp_only: + f, filename = tempfile.mkstemp(".icns") + os.close(f) convert_cmd = ["iconutil", "-c", "icns", "-o", filename, iconset] convert_proc = subprocess.Popen( convert_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL @@ -349,6 +353,10 @@ def _save(im, fp, filename): if retcode: raise subprocess.CalledProcessError(retcode, convert_cmd) + if fp_only: + with open(filename, "rb") as f: + fp.write(f.read()) + Image.register_open(IcnsImageFile.format, IcnsImageFile, lambda x: x[:4] == b"icns") Image.register_extension(IcnsImageFile.format, ".icns")
diff --git a/Tests/test_file_icns.py b/Tests/test_file_icns.py --- a/Tests/test_file_icns.py +++ b/Tests/test_file_icns.py @@ -55,6 +55,19 @@ def test_save_append_images(tmp_path): assert_image_equal(reread, provided_im) +@pytest.mark.skipif(sys.platform != "darwin", reason="Requires macOS") +def test_save_fp(): + fp = io.BytesIO() + + with Image.open(TEST_FILE) as im: + im.save(fp, format="ICNS") + + with Image.open(fp) as reread: + assert reread.mode == "RGBA" + assert reread.size == (1024, 1024) + assert reread.format == "ICNS" + + def test_sizes(): # Check that we can load all of the sizes, and that the final pixel # dimensions are as expected
CalledProcessError saving icns file to io.BytesIO() Currently, writing an icns file to an io.ByteIO object fails. This operation is supported by other filetypes (jpg, png, ico, etc) so I'm not clear if this report falls under feature request or bug ### What did you do? Write icns file to io.BytesIO() object ```python from PIL import Image import io import base64 im = Image.new(mode="RGBA", size=(256,256), color=(0,100,246,255)) f = io.BytesIO() im.save(fp=f, format="icns") b64 = base64.b64encode(f.getvalue()).decode() print(f'Image: {b64}') ``` ### What did you expect to happen? Fill the io.BytesIO object ### What actually happened? macOS's iconutil failed because it was provided an empty filename for output (-o) ```bash subprocess.CalledProcessError: Command '['iconutil', '-c', 'icns', '-o', '', '/var/folders/91/q75bkgks1196cr1rsr0399540000gn/T/tmppmsm3z2y.iconset']' returned non-zero exit status 1. ``` I believe one solution would be if `filename` variable is empty then use a dummy name and after popen returns, read the file from disk. ### What are your OS, Python and Pillow versions? * OS: macOS Mojave 10.14.6 * Python: 3.7.7 * Pillow: 7.1.2
This would be fixed by merging #4526.
2020-06-28T07:27:27Z
7.1
python-pillow/Pillow
4,664
python-pillow__Pillow-4664
[ "4177" ]
ba58ae752c742f891d5c0a7a7162ec39debd9437
diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -259,7 +259,7 @@ def getsize( :return: (width, height) """ - size, offset = self.font.getsize(text, direction, features, language) + size, offset = self.font.getsize(text, False, direction, features, language) return ( size[0] + stroke_width * 2 + offset[0], size[1] + stroke_width * 2 + offset[1], @@ -468,7 +468,9 @@ def getmask2( :py:mod:`PIL.Image.core` interface module, and the text offset, the gap between the starting coordinate and the first marking """ - size, offset = self.font.getsize(text, direction, features, language) + size, offset = self.font.getsize( + text, mode == "1", direction, features, language + ) size = size[0] + stroke_width * 2, size[1] + stroke_width * 2 im = fill("L", size, 0) self.font.render(
diff --git a/Tests/images/text_mono.gif b/Tests/images/text_mono.gif new file mode 100644 Binary files /dev/null and b/Tests/images/text_mono.gif differ diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -11,6 +11,7 @@ from .helper import ( assert_image_equal, + assert_image_equal_tofile, assert_image_similar, assert_image_similar_tofile, is_pypy, @@ -724,3 +725,19 @@ def _check_text(font, path, epsilon): @skip_unless_feature("raqm") class TestImageFont_RaqmLayout(TestImageFont): LAYOUT_ENGINE = ImageFont.LAYOUT_RAQM + + +def test_render_mono_size(): + # issue 4177 + + if distutils.version.StrictVersion(ImageFont.core.freetype2_version) < "2.4": + pytest.skip("Different metrics") + + im = Image.new("P", (100, 30), "white") + draw = ImageDraw.Draw(im) + ttf = ImageFont.truetype( + "Tests/fonts/DejaVuSans.ttf", 18, layout_engine=ImageFont.LAYOUT_BASIC + ) + + draw.text((10, 10), "r" * 10, "black", ttf) + assert_image_equal_tofile(im, "Tests/images/text_mono.gif")
Truetype fonts not being rendered correctly with the TEXT method ### What did you do? Created an image suitable for the Pimoroni InkyHat display Added italic text onto the image object at different places ### What did you expect to happen? The whole of the last character of the text to be displayed as it did to render correctly on Stretch on the Pi Zero Looking at the font from a Mac (Mojave), the characters look fine. ### What actually happened? Depending on the length of the text, some or all of the last character is missing when using some italic fonts. If the text length is around 105 - 110 pixels then you can lose some / all of the very last character. **Padding out the text string with spaces so it is longer than 110 pixels fixes the issue** ### What are your OS, Python and Pillow versions? * OS: Raspbian Buster Lite (10.1) Kernel 4.19.75+ #1270 Tue Sep 24 18:38:54 BST 2019 armv6l GNU/Linux (running on a Pi Zero) * Python: 3.7.3 - not tested under Python 2 * Pillow: 6.2.1 (installed using pip3) The fonts used are available from [Font Squirrel](https://www.fontsquirrel.com) - the two are: Open Sans [here](https://www.fontsquirrel.com/fonts/open-sans) Ubuntu [here](https://www.fontsquirrel.com/fonts/ubuntu?q%5Bterm%5D=ubuntu&q%5Bsearch_check%5D=Y) ```python from PIL import Image, ImageDraw, ImageFont image_obj = Image.new('P', (212, 104), color = (255,255,255)) screen_image = ImageDraw.Draw(image_obj) osbi = ImageFont.truetype('Fonts/OpenSans-BoldItalic.ttf', 15) screen_image.text((10,10), 'Network Status test',fill = (0,0,0) , font = osbi) screen_image.text((10,30), 'Bit longer no iffy ending',fill = (0,0,0) , font = osbi) ubuntu = ImageFont.truetype('Fonts/Ubuntu-BI.ttf', 15) screen_image.text((10,60), 'Network Status test',fill = (0,0,0) , font = ubuntu) screen_image.text((10,80), 'Bit longer no iffy ending',fill = (0,0,0) , font = ubuntu) image_obj.save('italic-test.png') ``` ![italic-test](https://user-images.githubusercontent.com/39886283/67718207-2ec54880-f9c7-11e9-90c7-a77f70050e8e.png)
Have now discovered that: 1) It is not only Italic fonts (can reproduce on various 'light' fonts) 2) The range of ending positions is not limited to 110 Pixels - I now have one at 129 pixels I can replicate this error on macOS with updated libs. I've seen issues similar to this using Pillow to render text for little 1-bit OLED displays. It looks like Pillow is using fontmode='1' since you have chosen mode 'P'. What happens if you use 'L' or 'RGB' instead of 'P'? If you add `screen_image.fontmode='L'` before rendering text does the problem go away? This may be related to https://github.com/python-pillow/Pillow/issues/2293 (i.e. it may be a libfreetype problem).
2020-06-01T20:53:06Z
7.1
python-pillow/Pillow
4,605
python-pillow__Pillow-4605
[ "3677" ]
794e9f0f0e85535e6bd1791e2ec127dec345f319
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -553,9 +553,10 @@ def _setitem(self, tag, value, legacy_api): ) elif all(isinstance(v, float) for v in values): self.tagtype[tag] = TiffTags.DOUBLE - else: - if all(isinstance(v, str) for v in values): - self.tagtype[tag] = TiffTags.ASCII + elif all(isinstance(v, str) for v in values): + self.tagtype[tag] = TiffTags.ASCII + elif all(isinstance(v, bytes) for v in values): + self.tagtype[tag] = TiffTags.BYTE if self.tagtype[tag] == TiffTags.UNDEFINED: values = [ @@ -573,8 +574,10 @@ def _setitem(self, tag, value, legacy_api): # Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed. # No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple. # Don't mess with the legacy api, since it's frozen. - if (info.length == 1) or ( - info.length is None and len(values) == 1 and not legacy_api + if ( + (info.length == 1) + or self.tagtype[tag] == TiffTags.BYTE + or (info.length is None and len(values) == 1 and not legacy_api) ): # Don't mess with the legacy api, since it's frozen. if legacy_api and self.tagtype[tag] in [ @@ -1546,16 +1549,17 @@ def _save(im, fp, filename): # Custom items are supported for int, float, unicode, string and byte # values. Other types and tuples require a tagtype. if tag not in TiffTags.LIBTIFF_CORE: - if ( - TiffTags.lookup(tag).type == TiffTags.UNDEFINED - or not Image.core.libtiff_support_custom_tags - ): + if not Image.core.libtiff_support_custom_tags: continue if tag in ifd.tagtype: types[tag] = ifd.tagtype[tag] elif not (isinstance(value, (int, float, str, bytes))): continue + else: + type = TiffTags.lookup(tag).type + if type: + types[tag] = type if tag not in atts and tag not in blocklist: if isinstance(value, str): atts[tag] = value.encode("ascii", "replace") + b"\0"
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -299,9 +299,6 @@ def check_tags(tiffinfo): ) continue - if libtiff and isinstance(value, bytes): - value = value.decode() - assert reloaded_value == value # Test with types @@ -322,6 +319,17 @@ def check_tags(tiffinfo): ) TiffImagePlugin.WRITE_LIBTIFF = False + def test_xmlpacket_tag(self, tmp_path): + TiffImagePlugin.WRITE_LIBTIFF = True + + out = str(tmp_path / "temp.tif") + hopper().save(out, tiffinfo={700: b"xmlpacket tag"}) + TiffImagePlugin.WRITE_LIBTIFF = False + + with Image.open(out) as reloaded: + if 700 in reloaded.tag_v2: + assert reloaded.tag_v2[700] == b"xmlpacket tag" + def test_int_dpi(self, tmp_path): # issue #1765 im = hopper("RGB") @@ -667,6 +675,26 @@ def test_read_icc(self): TiffImagePlugin.READ_LIBTIFF = False assert icc == icc_libtiff + def test_write_icc(self, tmp_path): + def check_write(libtiff): + TiffImagePlugin.WRITE_LIBTIFF = libtiff + + with Image.open("Tests/images/hopper.iccprofile.tif") as img: + icc_profile = img.info["icc_profile"] + + out = str(tmp_path / "temp.tif") + img.save(out, icc_profile=icc_profile) + with Image.open(out) as reloaded: + assert icc_profile == reloaded.info["icc_profile"] + + libtiffs = [] + if Image.core.libtiff_support_custom_tags: + libtiffs.append(True) + libtiffs.append(False) + + for libtiff in libtiffs: + check_write(libtiff) + def test_multipage_compression(self): with Image.open("Tests/images/compression.tif") as im: diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py --- a/Tests/test_file_tiff_metadata.py +++ b/Tests/test_file_tiff_metadata.py @@ -319,13 +319,13 @@ def test_empty_values(): def test_PhotoshopInfo(tmp_path): with Image.open("Tests/images/issue_2278.tif") as im: - assert len(im.tag_v2[34377]) == 1 - assert isinstance(im.tag_v2[34377][0], bytes) + assert len(im.tag_v2[34377]) == 70 + assert isinstance(im.tag_v2[34377], bytes) out = str(tmp_path / "temp.tiff") im.save(out) with Image.open(out) as reloaded: - assert len(reloaded.tag_v2[34377]) == 1 - assert isinstance(reloaded.tag_v2[34377][0], bytes) + assert len(reloaded.tag_v2[34377]) == 70 + assert isinstance(reloaded.tag_v2[34377], bytes) def test_too_many_entries():
Saving TIFF with compression throws Segmentation Fault 11 in 5.4.1, but not 5.3.0 ### What did you do? Opened a bitonal TIFF created with Adobe Photoshop CC (version 20.0.2) then saved it with Group4 compression using Pillow. TIFF Image should be downloadable from Github repository here: [https://github.com/photosbyjeremy/images/blob/master/test_bitonal_text.tif.zip](https://github.com/photosbyjeremy/images/blob/master/test_bitonal_text.tif.zip) ### What did you expect to happen? I expected the image to save with compression. ### What actually happened? In Pillow 5.4.1 there was a Segmentation Fault 11, but in Pillow 5.3.0 it works just fine. <img width="624" alt="screen shot 2019-02-25 at 2 09 47 pm" src="https://user-images.githubusercontent.com/5132339/53362031-406dc200-3907-11e9-95b3-d9ae4724db9a.png"> <img width="640" alt="screen shot 2019-02-25 at 2 09 50 pm" src="https://user-images.githubusercontent.com/5132339/53362045-495e9380-3907-11e9-8334-9523cc340dde.png"> ### What are your OS, Python and Pillow versions? * OS: macOS 10.14.3 * Python: 3.6.8 (and I actually tried 3.7.1 first, but didn't screenshot those attempts) * Pillow: 5.4.1 and 5.3.0 Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as plone, Django, or buildout, try to replicate the issue just using Pillow. ```python from PIL import Image image = Image.open('test_bitonal_text.tif') image.save('test_pillow_save.tif', compression='group4') ```
<img width="668" alt="screen shot 2019-02-25 at 2 43 28 pm" src="https://user-images.githubusercontent.com/5132339/53363987-ce4bac00-390b-11e9-836e-c71b450beb85.png"> Git bisect points to https://github.com/python-pillow/Pillow/commit/6ead422e91bec1facc644f02bc25a561d0a02383 from PR https://github.com/python-pillow/Pillow/pull/3513. ```console $ python3 3677.py Python(31119,0x7fffb3bf1380) malloc: *** mach_vm_map(size=18446744072426508288) failed (error code=3) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug test_pillow_save.tif: Failed to allocate memory for custom tag binary object (-1283043808 elements of 1 bytes each). Traceback (most recent call last): File "3677.py", line 3, in <module> image.save('test_pillow_save.tif', compression='group4') File "/Users/hugo/github/Pillow/src/PIL/Image.py", line 1988, in save save_handler(self, fp, filename) File "/Users/hugo/github/Pillow/src/PIL/TiffImagePlugin.py", line 1552, in _save e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig) File "/Users/hugo/github/Pillow/src/PIL/Image.py", line 477, in _getencoder return encoder(mode, *args + extra) RuntimeError: Error setting from dictionary ``` * OS: macOS High Sierra 10.13.6 * Python: 3.7.2 If I replace the code in PIL.TiffImagePlugin.py changed by [6ead422]( https://github.com/python-pillow/Pillow/commit/6ead422e91bec1facc644f02bc25a561d0a02383) with that from 5.3.0 the save succeeds in 5.4.1 LEFT: TiffImagePlugin.py from 5.4.1 that works RIGHT: TiffImagePlugin.py from 5.3.0 that works <img width="1151" alt="screen shot 2019-02-25 at 4 01 25 pm" src="https://user-images.githubusercontent.com/5132339/53368528-10c6b600-3917-11e9-80b0-11acf9bcc6fa.png"> I have found the problematic tags. The following code runs without error. ```python from PIL import Image image = Image.open('test_bitonal_text.tif') del image.tag_v2[34377] del image.tag_v2[33723] del image.tag_v2[700] image.save('test_pillow_save.tif', compression='group4') ``` The following code is all that is needed to reproduce the segmentation fault. ```python from PIL import Image, TiffImagePlugin TiffImagePlugin.WRITE_LIBTIFF = True image = Image.new("RGB", (100, 100)) image.save('out.tif', tiffinfo={700: b"a"}) ``` The test suite is able to save byte data for other tag numbers, so the problem is specific to these numbers. The seg fault is occuring at https://github.com/python-pillow/Pillow/blob/d167f9e0bd8a71f7d0a5a1098dc9d51eceb67be2/src/libImaging/TiffDecode.c#L432 While an error still occurs for this issue, the segfault has been fixed in #4033 The error now received here is ```python from PIL import Image image = Image.open('test_bitonal_text.tif') image.save('test_pillow_save.tif', compression='group4') ``` ``` TypeError: an integer is required (got type bytes) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "code.py", line 3, in <module> image.save('test_pillow_save.tif', compression='group4') File "PIL/Image.py", line 2054, in save File "PIL/TiffImagePlugin.py", line 1598, in _save File "PIL/Image.py", line 428, in _getencoder SystemError: <built-in function libtiff_encoder> returned a result with an error set ``` Also getting the `SystemError: <built-in function libtiff_encoder> returned a result with an error set` when daving a tif file through `tesserocr`. Anyone with a solution yet? I'm actually working on a solution at the moment. To be sure that your problem is solved though, in case your error is triggered by a different case than the one in this issue, could we have a simple self-contained example of your situation? > I'm actually working on a solution at the moment. To be sure that your problem is solved though, in case your error is triggered by a different case than the one in this issue, could we have a simple self-contained example of your situation? it gets triggered when performing OCR on a tiff PIL image via the `tesserocr` library. SOmething like: ```python import tesserocr from tesserocr import PSM tesserocr.image_to_text(scanned_tiff_img, psm=PSM.SPARSE_TEXT_OSD) ``` Then I get `SystemError: <built-in function libtiff_encoder> returned a result with an error set`. From what I remember from looking at the stacktrace, it jammed when the library tried to save the tiff. My version of PIL is 7.1.2 @zoj613 Please could you post the full stacktrace? FWIW, I am getting the same error on the following snippet: ```python from PIL import Image, TiffImagePlugin image = Image.open('mytiff.tif') image.save('test_pillow_save.tif') ``` with the following stracktrace: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: an integer is required (got type bytes) The above exception was the direct cause of the following exception: SystemError Traceback (most recent call last) <ipython-input-27-3b2a40a8e19e> in <module> ----> 1 image.save('test_pillow_save.tif') ~/miniconda3/envs/fw/lib/python3.7/site-packages/PIL/Image.py in save(self, fp, format, **params) 2100 2101 try: -> 2102 save_handler(self, fp, filename) 2103 finally: 2104 # do what we can to clean up ~/miniconda3/envs/fw/lib/python3.7/site-packages/PIL/TiffImagePlugin.py in _save(im, fp, filename) 1614 tags.sort() 1615 a = (rawmode, compression, _fp, filename, tags, types) -> 1616 e = Image._getencoder(im.mode, "libtiff", a, im.encoderconfig) 1617 e.setimage(im.im, (0, 0) + im.size) 1618 while True: ~/miniconda3/envs/fw/lib/python3.7/site-packages/PIL/Image.py in _getencoder(mode, encoder_name, args, extra) 429 # get encoder 430 encoder = getattr(core, encoder_name + "_encoder") --> 431 return encoder(mode, *args + extra) 432 except AttributeError: 433 raise OSError("encoder %s not available" % encoder_name) SystemError: <built-in function libtiff_encoder> returned a result with an error set ``` OS: macOS 10.14.6 Python: 3.7.5 Pillow: 7.0.0 and 7.1.2 I've created PR #4605 to resolve this. @zoj613 @NPann if you could check and confirm that this also resolves your situations. If it does not, please provide images to demonstrate the problem. @radarhere, it does resolve my situation. Thanks a lot for figuring this out!
2020-05-03T10:10:52Z
7.1
python-pillow/Pillow
4,474
python-pillow__Pillow-4474
[ "4343" ]
64e7d72ee8b4a95a3ebc3f255f0f3d3de913b1ea
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1866,7 +1866,11 @@ def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None): factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) - self = self.reduce((factor_x, factor_y), box=reduce_box) + factor = (factor_x, factor_y) + if callable(self.reduce): + self = self.reduce(factor, box=reduce_box) + else: + self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, diff --git a/src/PIL/Jpeg2KImagePlugin.py b/src/PIL/Jpeg2KImagePlugin.py --- a/src/PIL/Jpeg2KImagePlugin.py +++ b/src/PIL/Jpeg2KImagePlugin.py @@ -176,7 +176,7 @@ def _open(self): if self.size is None or self.mode is None: raise SyntaxError("unable to determine size/mode") - self.reduce = 0 + self._reduce = 0 self.layers = 0 fd = -1 @@ -200,23 +200,33 @@ def _open(self): "jpeg2k", (0, 0) + self.size, 0, - (self.codec, self.reduce, self.layers, fd, length), + (self.codec, self._reduce, self.layers, fd, length), ) ] + @property + def reduce(self): + # https://github.com/python-pillow/Pillow/issues/4343 found that the + # new Image 'reduce' method was shadowed by this plugin's 'reduce' + # property. This attempts to allow for both scenarios + return self._reduce or super().reduce + + @reduce.setter + def reduce(self, value): + self._reduce = value + def load(self): - if self.reduce: - power = 1 << self.reduce + if self.tile and self._reduce: + power = 1 << self._reduce adjust = power >> 1 self._size = ( int((self.size[0] + adjust) / power), int((self.size[1] + adjust) / power), ) - if self.tile: # Update the reduce and layers settings t = self.tile[0] - t3 = (t[3][0], self.reduce, self.layers, t[3][3], t[3][4]) + t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4]) self.tile = [(t[0], (0, 0) + self.size, t[2], t3)] return ImageFile.ImageFile.load(self)
diff --git a/Tests/test_file_jpeg2k.py b/Tests/test_file_jpeg2k.py --- a/Tests/test_file_jpeg2k.py +++ b/Tests/test_file_jpeg2k.py @@ -127,10 +127,17 @@ def test_prog_res_rt(): def test_reduce(): with Image.open("Tests/images/test-card-lossless.jp2") as im: + assert callable(im.reduce) + im.reduce = 2 + assert im.reduce == 2 + im.load() assert im.size == (160, 120) + im.thumbnail((40, 40)) + assert im.size == (40, 30) + def test_layers_type(tmp_path): outfile = str(tmp_path / "temp_layers.jp2") diff --git a/Tests/test_image_reduce.py b/Tests/test_image_reduce.py --- a/Tests/test_image_reduce.py +++ b/Tests/test_image_reduce.py @@ -3,6 +3,9 @@ from .helper import convert_to_comparable +codecs = dir(Image.core) + + # There are several internal implementations remarkable_factors = [ # special implementations @@ -247,3 +250,11 @@ def test_mode_F(): for factor in remarkable_factors: compare_reduce_with_reference(im, factor, 0, 0) compare_reduce_with_box(im, factor) + + +@pytest.mark.skipif( + "jpeg2k_decoder" not in codecs, reason="JPEG 2000 support not available" +) +def test_jpeg2k(): + with Image.open("Tests/images/test-card-lossless.jp2") as im: + assert im.reduce(2).size == (320, 240)
JPEG 2000 file cannot be Image.reduce() 'd JPEG 2000 file cannot be Image.reduce() 'd ... because img.reduce becomes a integer 0 during loading somehow. Can be repeated with [this image](https://drive.google.com/open?id=1UbSkNdOuUCt50TTu7Zc4PnuP6f-5RkKK) ``` $ python -c 'import PIL;from PIL import Image; im = Image.open("pillow_bug.jp2"); print(PIL.__version__);print(im.reduce)' 7.1.0.dev0 0 ```
Hi. Thanks for reporting this. The bug you've found applies to Jpeg2000 images. #4251 added an Image `reduce` method which is here overlapping with Jpeg2KImagePlugin's `reduce` property. I've created PR #4344 to resolve the situation. In the meantime, you can workaround this by simply copying the image first - ```python from PIL import Image im = Image.open("pillow_bug.jp2") im.copy().reduce(2) ``` Unfortunately, this breaks a very common use case: ```python Image.open("pillow_bug.jp2").thumbnail((100, 100)) ``` because thumbnail now uses `.reduce()` method internal.
2020-03-14T12:18:58Z
7
python-pillow/Pillow
4,471
python-pillow__Pillow-4471
[ "4460" ]
ca00126e2b5eafb742994bb56df351c5b9f473c2
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -694,14 +694,24 @@ def load_end(self): def _getexif(self): if "exif" not in self.info: self.load() - if "exif" not in self.info: + if "exif" not in self.info and "Raw profile type exif" not in self.info: return None return dict(self.getexif()) def getexif(self): if "exif" not in self.info: self.load() - return ImageFile.ImageFile.getexif(self) + + if self._exif is None: + self._exif = Image.Exif() + + exif_info = self.info.get("exif") + if exif_info is None and "Raw profile type exif" in self.info: + exif_info = bytes.fromhex( + "".join(self.info["Raw profile type exif"].split("\n")[3:]) + ) + self._exif.load(exif_info) + return self._exif # --------------------------------------------------------------------
diff --git a/Tests/images/exif_imagemagick.png b/Tests/images/exif_imagemagick.png new file mode 100644 Binary files /dev/null and b/Tests/images/exif_imagemagick.png differ diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -592,8 +592,15 @@ def test_textual_chunks_after_idat(self): with Image.open("Tests/images/hopper_idat_after_image_end.png") as im: assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"} - def test_exif(self): - with Image.open("Tests/images/exif.png") as im: + @pytest.mark.parametrize( + "test_file", + [ + "Tests/images/exif.png", # With an EXIF chunk + "Tests/images/exif_imagemagick.png", # With an ImageMagick zTXt chunk + ], + ) + def test_exif(self, test_file): + with Image.open(test_file) as im: exif = im._getexif() assert exif[274] == 1
PngStream does not decode EXIF data from "Raw profile" tags <!-- Thank you for reporting an issue. Follow these guidelines to ensure your issue is handled properly. If you have a ... 1. General question: consider asking the question on Stack Overflow with the python-imaging-library tag: * https://stackoverflow.com/questions/tagged/python-imaging-library Do not ask a question in both places. If you think you have found a bug or have an unexplained exception then file a bug report here. 2. Bug report: include a self-contained, copy-pastable example that generates the issue if possible. Be concise with code posted. Guidelines on how to provide a good bug report: * https://stackoverflow.com/help/mcve Bug reports which follow these guidelines are easier to diagnose, and are often handled much more quickly. 3. Feature request: do a quick search of existing issues to make sure this has not been asked before. We know asking good questions takes effort, and we appreciate your time. Thank you. --> ### What did you do? I attempted to read the meta-data from one of the test images from Exiv2 ("ReaganSmallPng.png"). This file contains EXIF and IPTC meta-data stored under compressed "Raw profile type" tags, typical of ImageMagick (and possibly other software). ### What did you expect to happen? - The Image's info["exif"] contains the EXIF data, and getexif() returns an object containing some or all of the meta-data, **or** - The Image's info["Raw profile type exif"] contains the EXIF data, which can be manually fed back into info["exif"] ### What actually happened? The Image's info["exif"] was empty, and getexif() returned no metadata. The "Raw profile type exif" was read, but was not suitable to be used as info["exif"]. (Attempting this produces a SyntaxError in the TiffImagePlugin, which I haven't investigated further.) I tried modifying PngStream.chunk_zTXt in "PngImagePlugin.py" to skip decoding the bytes as "latin-1", but I still got the same SyntaxError. ``` Found Exif tags: 0 Traceback (most recent call last): File "pil_err.py", line 9, in <module> exif = reagan.getexif() File "/usr/lib64/python3.6/site-packages/PIL/PngImagePlugin.py", line 704, in getexif return ImageFile.ImageFile.getexif(self) File "/usr/lib64/python3.6/site-packages/PIL/Image.py", line 1275, in getexif self._exif.load(self.info.get("exif")) File "/usr/lib64/python3.6/site-packages/PIL/Image.py", line 3237, in load self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head) File "/usr/lib64/python3.6/site-packages/PIL/TiffImagePlugin.py", line 900, in __init__ super().__init__(*args, **kwargs) File "/usr/lib64/python3.6/site-packages/PIL/TiffImagePlugin.py", line 466, in __init__ raise SyntaxError("not a TIFF file (header %r not valid)" % ifh) SyntaxError: not a TIFF file (header b' 8526' not valid) ``` ### What are your OS, Python and Pillow versions? * OS: Gentoo Base System release 2.6, Linux kernel 4.19.97-gentoo x86_64 * Python: Python 3.6.10 * Pillow: Pillow 6.2.2 (from Gentoo), Pillow 7.0.0 (from Gentoo) <!-- Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow. --> ```python import PIL.Image reagan = PIL.Image.open("ReaganSmallPng.png") exif = reagan.getexif() print("Found Exif tags:", len(exif.keys())) reagan.info["exif"] = reagan.info['Raw profile type exif'].encode('latin-1') exif = reagan.getexif() print("Found Exif tags:", len(exif.keys())) ``` ### Image causing the issue ![ReaganSmallPng](https://raw.githubusercontent.com/Exiv2/exiv2/master/test/data/ReaganSmallPng.png) ### Additional information ImageMagick's PNG encoder: https://github.com/ImageMagick/ImageMagick/blob/master/coders/png.c ExifTool's guide to PNG Tags: https://exiftool.org/TagNames/PNG.html
I found https://sourceforge.net/p/png-mng/mailman/png-mng-misc/?viewmonth=201612&viewday=31 which pointed out that the data is hexencoded. So I find that this gives me 55 EXIF keys. ```python from PIL import Image reagan = Image.open("ReaganSmallPng.png") exif = reagan.getexif() print("Found Exif tags:", len(exif.keys())) reagan.info["exif"] = bytes.fromhex("".join(reagan.info['Raw profile type exif'].split("\n")[3:])) exif = reagan.getexif() print("Found Exif tags:", len(exif.keys())) ``` Thanks, that's what I was missing! With that as a "work-around", I think that this issue could be classified as a feature-request rather than a bug. Looking into this, ImageMagick implemented "Raw profile type exif" before Exif became part of the PNG standard - https://ask.xiaolee.net/questions/1122297. It doesn't write both - https://github.com/ImageMagick/ImageMagick/blob/868aad754ee599eb7153b84d610f2ecdf7b339f6/coders/png.c#L11068-L11071. So it seems reasonable to alter PngImagePlugin to read this as well. However, this means it is slightly harder to generate an image with a "Raw profile type exif", since ImageMagick hasn't written it in two years. Would you happen to have an image that could be included in the test suite under the Pillow license? I managed to create a file, and have created PR #4471 to resolve this.
2020-03-13T13:01:03Z
7
python-pillow/Pillow
4,283
python-pillow__Pillow-4283
[ "4274" ]
209faf1b62fa7ed6c9d8b2fc7bd46e1c7e54e0bd
diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -321,12 +321,15 @@ def _save(im, fp, filename, bitmap_header=True): # bitmap header if bitmap_header: offset = 14 + header + colors * 4 + file_size = offset + image + if file_size > 2 ** 32 - 1: + raise ValueError("File size is too large for the BMP format") fp.write( - b"BM" - + o32(offset + image) # file type (magic) - + o32(0) # file size - + o32(offset) # reserved - ) # image data offset + b"BM" # file type (magic) + + o32(file_size) # file size + + o32(0) # reserved + + o32(offset) # image data offset + ) # bitmap info header fp.write(
diff --git a/Tests/test_file_bmp.py b/Tests/test_file_bmp.py --- a/Tests/test_file_bmp.py +++ b/Tests/test_file_bmp.py @@ -41,6 +41,13 @@ def test_save_to_bytes(self): self.assertEqual(im.size, reloaded.size) self.assertEqual(reloaded.format, "BMP") + def test_save_too_large(self): + outfile = self.tempfile("temp.bmp") + with Image.new("RGB", (1, 1)) as im: + im._size = (37838, 37838) + with self.assertRaises(ValueError): + im.save(outfile) + def test_dpi(self): dpi = (72, 72)
Large BMP files crash (i.e. more than 2**32 pixels) I started asking on StackOverflow about my original problem, and the code is pasted over there: https://stackoverflow.com/questions/59353721/python-pillow-opening-1-bit-depth-files-with-8-bits but after moving to a larger machine (256 GB RAM) I moved on from the original issue and onto an Exception in the code. Basically I'm trying to save a 59GigaPixel single-channel (1 bit depth) BMP file, which is yielding this error: ``` Traceback (most recent call last): File "stitch_bmps.py", line 75, in <module> blank.save("59GP.bmp", "BMP") File "/home/nmz787/.local/lib/python3.7/site-packages/PIL/Image.py", line 2084, in save save_handler(self, fp, filename) File "/home/nmz787/.local/lib/python3.7/site-packages/PIL/BmpImagePlugin.py", line 332, in _save + o32(offset) # reserved File "/home/nmz787/.local/lib/python3.7/site-packages/PIL/_binary.py", line 91, in o32le return pack("<I", i) struct.error: 'I' format requires 0 <= number <= 4294967295 ``` Here's a small example to reproduce easily (requires at least 61GB of RAM, or RAM+swap): ```python from PIL import Image a = Image.new("1", (247246, 247246)) a.save("blank_59GP.bmp", "BMP") ``` ### What are your OS, Python and Pillow versions? * OS: Linux version 4.9.164-vs2.3.9.8-beng (root@ex64-jessie) (gcc version 4.9.2 (Debian 4.9.2-10+deb8u2) ) #1 SMP Wed Mar 20 20:18:21 GMT 2019 * PIP: 18.1 * Python: 3.7.3
Pillow Version: 6.2.1 Looks like BMP max filesize is limited to 4GiB. The second field in BMF file header is filesize in bytes, which is 4 bytes int, which can not exceed 2^32 (4GiB). Since your image is 1bpp image, with given dimensions image size would have to be 7,641,879,368 bytes, which exceeds 4 byte int capacity. Thanks for the clarification, can we get this notice added to the code during the `save` call, so it's absolutely clear what the problem is (user error).
2019-12-20T21:34:33Z
6.2
python-pillow/Pillow
4,240
python-pillow__Pillow-4240
[ "4099" ]
a9fc1b66b1fe1d699674350330af9cd0a9f4d277
diff --git a/src/PIL/MpoImagePlugin.py b/src/PIL/MpoImagePlugin.py --- a/src/PIL/MpoImagePlugin.py +++ b/src/PIL/MpoImagePlugin.py @@ -82,7 +82,10 @@ def seek(self, frame): self.offset = self.__mpoffsets[frame] self.fp.seek(self.offset + 2) # skip SOI marker - if i16(self.fp.read(2)) == 0xFFE1: # APP1 + segment = self.fp.read(2) + if not segment: + raise ValueError("No data found for frame") + if i16(segment) == 0xFFE1: # APP1 n = i16(self.fp.read(2)) - 2 self.info["exif"] = ImageFile._safe_read(self.fp, n)
diff --git a/Tests/images/sugarshack_no_data.mpo b/Tests/images/sugarshack_no_data.mpo new file mode 100644 Binary files /dev/null and b/Tests/images/sugarshack_no_data.mpo differ diff --git a/Tests/test_file_mpo.py b/Tests/test_file_mpo.py --- a/Tests/test_file_mpo.py +++ b/Tests/test_file_mpo.py @@ -113,6 +113,13 @@ def test_mp_offset(self): self.assertEqual(mpinfo[45056], b"0100") self.assertEqual(mpinfo[45057], 2) + def test_mp_no_data(self): + # This image has been manually hexedited to have the second frame + # beyond the end of the file + with Image.open("Tests/images/sugarshack_no_data.mpo") as im: + with self.assertRaises(ValueError): + im.seek(1) + def test_mp_attribute(self): for test_file in test_files: with Image.open(test_file) as im:
MPO seek error ### What did you do? I perform an `Image.seek` operation. ### What did you expect to happen? I expect a successful function invocation. ### What actually happened? I get an error: ``` ~/.local/share/virtualenvs/muffinchihuahua-VbII3yUl/lib/python3.7/site-packages/PIL/MpoImagePlugin.py in seek(self, frame) 89 if "parsed_exif" in self.info: 90 del self.info["parsed_exif"] ---> 91 if i16(self.fp.read(2)) == 0xFFE1: # APP1 92 n = i16(self.fp.read(2)) - 2 93 self.info["exif"] = ImageFile._safe_read(self.fp, n) ~/.local/share/virtualenvs/muffinchihuahua-VbII3yUl/lib/python3.7/site-packages/PIL/_binary.py in i16be(c, o) 75 76 def i16be(c, o=0): ---> 77 return unpack_from(">H", c, o)[0] 78 79 error: unpack_from requires a buffer of at least 2 bytes ``` ### What are your OS, Python and Pillow versions? * OS: macOs Mojave 10.14.6 * Python: 3.7 * Pillow: 6.1.0 ```python import urllib.request from PIL import Image urllib.request.urlretrieve('https://srv-file7.gofile.io/download/X30JBL/137.DSC_0733-3-blueberry-muffins-.jpg', 'muffin.jpg') im=Image.open('muffin.jpg') im.seek(0) im.seek(1) ```
If I navigate to https://srv-file7.gofile.io/download/X30JBL/137.DSC_0733-3-blueberry-muffins-.jpg in my browser, I get 'You are not authorized to download this file.' Hmm that's bizarre @radarhere. My browser (Chrome) just downloads the file. Same for Python if I run the above. Could you just attach the file in a GitHub comment? Yup, right here @radarhere ![muffin](https://user-images.githubusercontent.com/1505227/65825093-81281380-e227-11e9-8d6a-0ee326d766db.jpg) The updated snippet using the above GitHub attachment: ```python import urllib.request from PIL import Image urllib.request.urlretrieve('https://user-images.githubusercontent.com/1505227/65825093-81281380-e227-11e9-8d6a-0ee326d766db.jpg', 'muffin.jpg') im=Image.open('muffin.jpg') im.seek(0) im.seek(1) ``` Investigating, the offsets for the three images within the file are 0, 7353813 and 7386069. However, the file only has a size of 125510. So my simple theory is that this image is just truncated - it should be at least 7mb, but it's only 123kb. We could add a clearer error message, but I'm not seeing a way to get the image data. Feel free to prove me wrong by demonstrating a way to extract the image using another program, ideally exiftool.
2019-11-30T00:09:44Z
6.2
python-pillow/Pillow
4,063
python-pillow__Pillow-4063
[ "4053" ]
929c817014834e3569b6c2d7112641b8a48da216
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -1098,6 +1098,20 @@ def load(self): return super(TiffImageFile, self).load() def load_end(self): + if self._tile_orientation: + method = { + 2: Image.FLIP_LEFT_RIGHT, + 3: Image.ROTATE_180, + 4: Image.FLIP_TOP_BOTTOM, + 5: Image.TRANSPOSE, + 6: Image.ROTATE_270, + 7: Image.TRANSVERSE, + 8: Image.ROTATE_90, + }.get(self._tile_orientation) + if method is not None: + self.im = self.im.transpose(method) + self._size = self.im.size + # allow closing if we're on the first frame, there's no next # This is the ImageFile.load path only, libtiff specific below. if not self._is_animated: @@ -1181,6 +1195,9 @@ def _load_libtiff(self): self.tile = [] self.readonly = 0 + + self.load_end() + # libtiff closed the fp in a, we need to close self.fp, if possible if self._exclusive_fp and not self._is_animated: self.fp.close() @@ -1388,6 +1405,8 @@ def _setup(self): palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]] self.palette = ImagePalette.raw("RGB;L", b"".join(palette)) + self._tile_orientation = self.tag_v2.get(0x0112) + def _close__fp(self): try: if self.__fp != self.fp:
diff --git a/Tests/images/g4_orientation_1.tif b/Tests/images/g4_orientation_1.tif new file mode 100755 Binary files /dev/null and b/Tests/images/g4_orientation_1.tif differ diff --git a/Tests/images/g4_orientation_2.tif b/Tests/images/g4_orientation_2.tif new file mode 100755 Binary files /dev/null and b/Tests/images/g4_orientation_2.tif differ diff --git a/Tests/images/g4_orientation_3.tif b/Tests/images/g4_orientation_3.tif new file mode 100755 Binary files /dev/null and b/Tests/images/g4_orientation_3.tif differ diff --git a/Tests/images/g4_orientation_4.tif b/Tests/images/g4_orientation_4.tif new file mode 100755 Binary files /dev/null and b/Tests/images/g4_orientation_4.tif differ diff --git a/Tests/images/g4_orientation_5.tif b/Tests/images/g4_orientation_5.tif new file mode 100755 Binary files /dev/null and b/Tests/images/g4_orientation_5.tif differ diff --git a/Tests/images/g4_orientation_6.tif b/Tests/images/g4_orientation_6.tif new file mode 100755 Binary files /dev/null and b/Tests/images/g4_orientation_6.tif differ diff --git a/Tests/images/g4_orientation_7.tif b/Tests/images/g4_orientation_7.tif new file mode 100755 Binary files /dev/null and b/Tests/images/g4_orientation_7.tif differ diff --git a/Tests/images/g4_orientation_8.tif b/Tests/images/g4_orientation_8.tif new file mode 100755 Binary files /dev/null and b/Tests/images/g4_orientation_8.tif differ diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -831,3 +831,12 @@ def test_old_style_jpeg(self): self.assert_image_equal_tofile( im, "Tests/images/old-style-jpeg-compression.png" ) + + def test_orientation(self): + base_im = Image.open("Tests/images/g4_orientation_1.tif") + + for i in range(2, 9): + im = Image.open("Tests/images/g4_orientation_" + str(i) + ".tif") + im.load() + + self.assert_image_similar(base_im, im, 0.7)
TIFF orientation tag handled differently from most other software when loading G4 TIFF files Most image software handles TIFF orientation tags (tag 274) differently from Pillow when loading binary G4 TIFF images. This means that only images having the orientation tag == 1 (The 0th row represents the visual top of the image, and the 0th column represents the visual left-hand side) are loaded correctly (in the same way as in other software), other images should be corrected manually. I am not sure whether Pillow regards the orientation tags while other software ignores or vice versa. At least they are loaded transposed. I use Pillow-6.1.0 with Python 3.8 on Windows. I've developed the following procedure in my script to load TIFF files correctly (basically I only have files with orientation==8 from my office copier machine, so I have not tested other orientations). I think this something similar should be part of the TIFFImagePlugin ```python from PIL import Image from tkinter import filedialog, Tk ORIENTATION = 274 root = Tk() root.withdraw() file_selected = filedialog.askopenfilename() srcim = Image.open(filename) orientation = srcim.tag[ORIENTATION][0] format = os.path.splitext(filename)[1] if format.lower() in [".tif", ".tiff"]: try: if orientation == 8: srcim = srcim.transpose(Image.ROTATE_90) elif orientation == 3: srcim = srcim.transpose(Image.ROTATE_180) elif orientation == 6: srcim = srcim.transpose(Image.ROTATE_270) elif orientation == 2: srcim = srcim.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 4: srcim = srcim.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 5: srcim = srcim.transpose(Image.ROTATE_90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 7: srcim = srcim.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT) except: print("Can't detect orientation") ```
Hi. In Pillow 6.0, `ImageOps.exif_tranpose` was added - https://github.com/python-pillow/Pillow/blob/1e3c2c9ce1aea8536e95ce74086a79793e467618/src/PIL/ImageOps.py#L523-L530 So you should be able to simplify your code down to - ```python from PIL import Image, ImageOps from tkinter import filedialog, Tk root = Tk() root.withdraw() file_selected = filedialog.askopenfilename() srcim = Image.open(filename) srcim = ImageOps.exif_transpose(src_im) ``` If you're asking why this is not applied automatically, the answer would be that `ImageOps.exif_transpose` has not always been a part of Pillow, and we value backwards compatibility highly. Hi, thanks for the reply. No, `exif_transpose` does not help. I mean TIFF tags, not the EXIF, it is a different thing. Try loading this file with PIL It shows upright in most graphic software, but PIL displays it rotated, because it disregards the TIFF 274 tag (orientation) [test1.zip](https://github.com/python-pillow/Pillow/files/3587110/test1.zip) Here is the updated procedure for correcting TIFF file orientation: ```python from PIL import Image TIFFTAG_ORIENTATION = 274 def correct_tiff(srcim): try: orientation = srcim.tag[TIFFTAG_ORIENTATION][0] if orientation == 2: srcim = srcim.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 3: srcim = srcim.transpose(Image.ROTATE_180) elif orientation == 4: srcim = srcim.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 5: srcim = srcim.transpose(Image.TRANSPOSE) elif orientation == 6: srcim = srcim.transpose(Image.ROTATE_270) elif orientation == 7: srcim = srcim.transpose(Image.TRANSVERSE) elif orientation == 8: srcim = srcim.transpose(Image.ROTATE_90) except: pass return srcim ``` and a small test script with a full set of test files (tiff G4 and uncompressed) attached. [tiff orientation test.zip](https://github.com/python-pillow/Pillow/files/3587366/tiff.orientation.test.zip) Thanks for all that. Could any of those images be be added to the test suite, under the Pillow license? Yes, both code snippets and the images are absolutely free to use under any license. Okay. I've created #4062 to add an `ImageOps.auto_transpose` method. See what you think.
2019-09-13T13:10:42Z
6.1
python-pillow/Pillow
4,003
python-pillow__Pillow-4003
[ "4002" ]
d96f657328cdb864e011fb576529de8d849229c2
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -489,6 +489,11 @@ def _write_multiple_frames(im, fp, palette): offset = frame_data["bbox"][:2] _write_frame_data(fp, im_frame, offset, frame_data["encoderinfo"]) return True + elif "duration" in im.encoderinfo and isinstance( + im.encoderinfo["duration"], (list, tuple) + ): + # Since multiple frames will not be written, add together the frame durations + im.encoderinfo["duration"] = sum(im.encoderinfo["duration"]) def _save_all(im, fp, filename):
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -495,6 +495,26 @@ def test_identical_frames(self): # Assert that the new duration is the total of the identical frames self.assertEqual(reread.info["duration"], 4500) + def test_identical_frames_to_single_frame(self): + for duration in ([1000, 1500, 2000, 4000], (1000, 1500, 2000, 4000), 8500): + out = self.tempfile("temp.gif") + im_list = [ + Image.new("L", (100, 100), "#000"), + Image.new("L", (100, 100), "#000"), + Image.new("L", (100, 100), "#000"), + ] + + im_list[0].save( + out, save_all=True, append_images=im_list[1:], duration=duration + ) + reread = Image.open(out) + + # Assert that all frames were combined + self.assertEqual(reread.n_frames, 1) + + # Assert that the new duration is the total of the identical frames + self.assertEqual(reread.info["duration"], 8500) + def test_number_of_loops(self): number_of_loops = 2
GIF error for multiple duration values ### What did you do? Using same images and a list of durations to produce a gif ### What did you expect to happen? produce the gif the specified durations ### What actually happened? failed when saving ### What are your OS, Python and Pillow versions? * OS: win10 * Python: 3.6 * Pillow: 6.1.0 to reproduce, add following testcase to `Tests/test_file_gif.py`, then run `pytest Tests/test_file_gif.py` ```python def test_totally_identical_frames(self): duration_list = [1000, 1500, 2000, 4000] out = self.tempfile("temp.gif") image_path = "Tests/images/bc7-argb-8bpp_MipMaps-1.png" im_list = [ Image.open(image_path), Image.open(image_path), Image.open(image_path), Image.open(image_path), ] mask = Image.new("RGBA", im_list[0].size, (255, 255, 255, 0)) frames = [] for image in im_list: frames.append(Image.alpha_composite(mask, image)) # duration as list frames[0].save(out, save_all=True, append_images=frames[1:], optimize=False, duration=duration_list, loop=0, transparency=0) reread = Image.open(out) # Assert that the first three frames were combined self.assertEqual(reread.n_frames, 1) # Assert that the new duration is the total of the identical frames self.assertEqual(reread.info["duration"], 8500) ``` err info is: if "duration" in im.encoderinfo: duration = int(im.encoderinfo["duration"] / 10) TypeError: unsupported operand type(s) for /: 'list' and 'int' https://github.com/python-pillow/Pillow/blob/f3f45cfec50a44970f325e6ef1a2e4eaf2caa89e/src/PIL/GifImagePlugin.py#L473-L477 seems like we should copy duration info from `im_frames[0]` to `im` when `len(im_frames) == 1`
2019-08-02T00:58:04Z
6.1
python-pillow/Pillow
4,147
python-pillow__Pillow-4147
[ "4146" ]
97ea6898cadb23d281fd5e2fd0167902c00ae671
diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py --- a/src/PIL/JpegImagePlugin.py +++ b/src/PIL/JpegImagePlugin.py @@ -172,10 +172,11 @@ def APP(self, marker): # 1 dpcm = 2.54 dpi dpi *= 2.54 self.info["dpi"] = int(dpi + 0.5), int(dpi + 0.5) - except (KeyError, SyntaxError, ZeroDivisionError): + except (KeyError, SyntaxError, ValueError, ZeroDivisionError): # SyntaxError for invalid/unreadable EXIF # KeyError for dpi not included # ZeroDivisionError for invalid dpi rational value + # ValueError for x_resolution[0] being an invalid float self.info["dpi"] = 72, 72
diff --git a/Tests/images/invalid-exif-without-x-resolution.jpg b/Tests/images/invalid-exif-without-x-resolution.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/invalid-exif-without-x-resolution.jpg differ diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -634,6 +634,14 @@ def test_invalid_exif(self): # OSError for unidentified image. self.assertEqual(im.info.get("dpi"), (72, 72)) + def test_invalid_exif_x_resolution(self): + # When no x or y resolution is defined in EXIF + im = Image.open("Tests/images/invalid-exif-without-x-resolution.jpg") + + # This should return the default, and not a ValueError or + # OSError for an unidentified image. + self.assertEqual(im.info.get("dpi"), (72, 72)) + def test_ifd_offset_exif(self): # Arrange # This image has been manually hexedited to have an IFD offset of 10,
Specific image can be opened by browser, but not by Pillow 6.2 ### What did you do? Tried to open a .jpg image with PIL ### What did you expect to happen? The photo can be opened in a browser and on Preview in Mac ### What actually happened? ```python from PIL import Image Image.open("/Users/dir/Desktop/3-full.jpg") ``` ```Traceback (most recent call last): File "pillow_test.py", line 2, in <module> Image.open("/User/dir/Desktop/3-full.jpg") File "/User/dir/.pyenv/versions/3.6.6/lib/python3.6/site-packages/PIL/Image.py", line 2804, in open im = _open_core(fp, filename, prefix) File "/User/dir/.pyenv/versions/3.6.6/lib/python3.6/site-packages/PIL/Image.py", line 2790, in _open_core im = factory(fp, filename) File "/User/dir/.pyenv/versions/3.6.6/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 789, in jpeg_factory im = JpegImageFile(fp, filename) File "/User/dir/.pyenv/versions/3.6.6/lib/python3.6/site-packages/PIL/ImageFile.py", line 106, in __init__ self._open() File "/User/dir/.pyenv/versions/3.6.6/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 376, in _open handler(self, i) File "/User/dir/.pyenv/versions/3.6.6/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 165, in APP dpi = float(x_resolution[0]) / x_resolution[1] ValueError: could not convert string to float: '\x00' ``` ### What are your OS, Python and Pillow versions? * OS: mac OS * Python: 3.6.9 * Pillow: 6.2 For this particular image, I found out that the `x_resolution` is a byte string instead of an actual number. Therefore, we get the above error "ValueError: could not convert string to float: '\x00'" ``` (Pdb) x_resolution '\x00\x04\x95\x0c\x00\x00\x00\x01' ``` https://github.com/python-pillow/Pillow/pull/2632 mentioned that getting dpi shouldn't be broken if the exif is invalid. Therefore, I propose the change of adding `ValueError` to the block: ```python except (KeyError, SyntaxError, ZeroDivisionError): # SyntaxError for invalid/unreadable EXIF # KeyError for dpi not included # ZeroDivisionError for invalid dpi rational value self.info["dpi"] = 72, 72 ```
Could you attach the image, so that we can also reproduce the problem?
2019-10-17T17:06:22Z
6.2
python-pillow/Pillow
3,897
python-pillow__Pillow-3897
[ "3875" ]
a986fed5b445bc9586476167b08d46e19cba1bbc
diff --git a/src/PIL/IcnsImagePlugin.py b/src/PIL/IcnsImagePlugin.py --- a/src/PIL/IcnsImagePlugin.py +++ b/src/PIL/IcnsImagePlugin.py @@ -251,8 +251,6 @@ def _open(self): self.best_size[0] * self.best_size[2], self.best_size[1] * self.best_size[2], ) - # Just use this to see if it's loaded or not yet. - self.tile = ("",) @property def size(self): @@ -286,7 +284,8 @@ def load(self): ) Image.Image.load(self) - if not self.tile: + if self.im and self.im.size == self.size: + # Already loaded return self.load_prepare() # This is likely NOT the best way to do it, but whatever. @@ -298,11 +297,6 @@ def load(self): self.im = im.im self.mode = im.mode self.size = im.size - if self._exclusive_fp: - self.fp.close() - self.fp = None - self.icns = None - self.tile = () self.load_end() diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py --- a/src/PIL/IcoImagePlugin.py +++ b/src/PIL/IcoImagePlugin.py @@ -288,6 +288,9 @@ def size(self, value): self._size = value def load(self): + if self.im and self.im.size == self.size: + # Already loaded + return im = self.ico.getimage(self.size) # if tile is PNG, it won't really be loaded yet im.load()
diff --git a/Tests/images/hopper_draw.ico b/Tests/images/hopper_draw.ico new file mode 100644 Binary files /dev/null and b/Tests/images/hopper_draw.ico differ diff --git a/Tests/test_file_icns.py b/Tests/test_file_icns.py --- a/Tests/test_file_icns.py +++ b/Tests/test_file_icns.py @@ -61,11 +61,10 @@ def test_sizes(self): for w, h, r in im.info['sizes']: wr = w * r hr = h * r - im2 = Image.open(TEST_FILE) - im2.size = (w, h, r) - im2.load() - self.assertEqual(im2.mode, 'RGBA') - self.assertEqual(im2.size, (wr, hr)) + im.size = (w, h, r) + im.load() + self.assertEqual(im.mode, 'RGBA') + self.assertEqual(im.size, (wr, hr)) # Check that we cannot load an incorrect size with self.assertRaises(ValueError): diff --git a/Tests/test_file_ico.py b/Tests/test_file_ico.py --- a/Tests/test_file_ico.py +++ b/Tests/test_file_ico.py @@ -1,7 +1,7 @@ from .helper import PillowTestCase, hopper import io -from PIL import Image, IcoImagePlugin +from PIL import Image, ImageDraw, IcoImagePlugin TEST_ICO_FILE = "Tests/images/hopper.ico" @@ -90,3 +90,16 @@ def test_unexpected_size(self): im = self.assert_warning(UserWarning, Image.open, "Tests/images/hopper_unexpected.ico") self.assertEqual(im.size, (16, 16)) + + def test_draw_reloaded(self): + im = Image.open(TEST_ICO_FILE) + outfile = self.tempfile("temp_saved_hopper_draw.ico") + + draw = ImageDraw.Draw(im) + draw.line((0, 0) + im.size, '#f00') + im.save(outfile) + + im = Image.open(outfile) + im.save("Tests/images/hopper_draw.ico") + reloaded = Image.open("Tests/images/hopper_draw.ico") + self.assert_image_equal(im, reloaded)
Draw on a ico file without having to convert to png ### What did you do? Load an ico image, draw lines and save it. ### What did you expect to happen? I expect to get lines on the `.ico` image ### What actually happened? No lines ### The solution I have to load the `.ico` image, save it as a png , reload the png and finally draw the line on the png. ### Feature request That would be nice to be able to draw line on `.ico` files or if it's not possible to implement this workaround on the "back side" ### What are your OS, Python and Pillow versions? * OS: Windows 10 * Python: 3.6 * Pillow: 5.1.0 ```python from PIL import Image, ImageDraw,ImageFont #create an ico file: this step is just for debug, I already have a `ico` file img = Image.new('RGB', (50, 50), (125, 167, 242)) img.save('a1.ico') #code start here im = Image.open('a1.ico').save('a1.png') im = Image.open('a1.png') d = ImageDraw.Draw(im) d.line((0, 0) + im.size, fill=128) d.line((0, im.size[1], im.size[0], 0), fill=128) im.save('pil_modif.ico') ```
Thanks for reporting this problem. For your immediate use until this is resolved, I can suggest using `im.copy()` instead of needing to save it and then load it again - ```python from PIL import Image, ImageDraw,ImageFont #create an ico file: this step is just for debug, I already have a `ico` file img = Image.new('RGB', (50, 50), (125, 167, 242)) img.save('a1.ico') #code start here im = Image.open('a1.ico') im = im.copy() d = ImageDraw.Draw(im) d.line((0, 0) + im.size, fill=128) d.line((0, im.size[1], im.size[0], 0), fill=128) im.save('pil_modif.ico') ```
2019-06-10T15:35:24Z
6
python-pillow/Pillow
3,859
python-pillow__Pillow-3859
[ "3849" ]
169961649d1d946c95155d4f046b8cbcdff49e61
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1794,7 +1794,18 @@ def resize(self, size, resample=NEAREST, box=None): if resample not in ( NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING, ): - raise ValueError("unknown resampling filter") + message = "Unknown resampling filter ({}).".format(resample) + + filters = ["{} ({})".format(filter[1], filter[0]) for filter in ( + (NEAREST, "Image.NEAREST"), + (LANCZOS, "Image.LANCZOS"), + (BILINEAR, "Image.BILINEAR"), + (BICUBIC, "Image.BICUBIC"), + (BOX, "Image.BOX"), + (HAMMING, "Image.HAMMING") + )] + raise ValueError( + message+" Use "+", ".join(filters[:-1])+" or "+filters[-1]) size = tuple(size) @@ -2263,7 +2274,22 @@ def __transformer(self, box, image, method, data, raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): - raise ValueError("unknown resampling filter") + if resample in (BOX, HAMMING, LANCZOS): + message = { + BOX: "Image.BOX", + HAMMING: "Image.HAMMING", + LANCZOS: "Image.LANCZOS/Image.ANTIALIAS" + }[resample]+" ({}) cannot be used.".format(resample) + else: + message = "Unknown resampling filter ({}).".format(resample) + + filters = ["{} ({})".format(filter[1], filter[0]) for filter in ( + (NEAREST, "Image.NEAREST"), + (BILINEAR, "Image.BILINEAR"), + (BICUBIC, "Image.BICUBIC") + )] + raise ValueError( + message+" Use "+", ".join(filters[:-1])+" or "+filters[-1]) image.load()
diff --git a/Tests/test_image_transform.py b/Tests/test_image_transform.py --- a/Tests/test_image_transform.py +++ b/Tests/test_image_transform.py @@ -160,6 +160,15 @@ def test_missing_method_data(self): im = hopper() self.assertRaises(ValueError, im.transform, (100, 100), None) + def test_unknown_resampling_filter(self): + im = hopper() + (w, h) = im.size + for resample in (Image.BOX, "unknown"): + self.assertRaises(ValueError, im.transform, (100, 100), Image.EXTENT, + (0, 0, + w, h), + resample) + class TestImageTransformAffine(PillowTestCase): transform = Image.AFFINE
"Unknown resampling filter" error message can be improved https://github.com/python-pillow/Pillow/blob/2766d943a1a39ea5beafd3cc10b115f5b608a9ab/src/PIL/Image.py#L1797 https://github.com/python-pillow/Pillow/blob/2766d943a1a39ea5beafd3cc10b115f5b608a9ab/src/PIL/Image.py#L2266 1. "unknown" feels vague/wrong. The resampling filter may very well be a valid one that Pillow is aware of _in general_, it's just that it's _unsupported_ for the current use-case. 2. The error could include both the sampling filter passed in _and_ what filters are supported/expected. Both of these are currently hard to gleam without reading the source code.
1. `resize` supports all the available filters, so in that case, the supplied filter is unknown. 2. When you say that it is hard to determine which filters are supported without reading the source code, https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.transform and https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.resize list the relevant filters.
2019-05-20T20:09:35Z
6
python-pillow/Pillow
3,825
python-pillow__Pillow-3825
[ "3823" ]
c15dc4d7cafc1147a7353480d4b81c90c82ec68d
diff --git a/src/PIL/Image.py b/src/PIL/Image.py --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2643,10 +2643,10 @@ def open(fp, mode="r"): exclusive_fp = False filename = "" - if isPath(fp): - filename = fp - elif HAS_PATHLIB and isinstance(fp, Path): + if HAS_PATHLIB and isinstance(fp, Path): filename = str(fp.resolve()) + elif isPath(fp): + filename = fp if filename: fp = builtins.open(filename, "rb")
diff --git a/Tests/test_image.py b/Tests/test_image.py --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -76,6 +76,10 @@ def test_bad_mode(self): @unittest.skipUnless(Image.HAS_PATHLIB, "requires pathlib/pathlib2") def test_pathlib(self): from PIL.Image import Path + im = Image.open(Path("Tests/images/multipage-mmap.tiff")) + self.assertEqual(im.mode, "P") + self.assertEqual(im.size, (10, 10)) + im = Image.open(Path("Tests/images/hopper.jpg")) self.assertEqual(im.mode, "RGB") self.assertEqual(im.size, (128, 128))
On Windows, opening a TIFF with a pathlib.Path argument fails ### What did you do? 1. Create a tiff file (e.g. `from pylab import *; savefig("test.tiff")` using matplotlib). 2. Try to load it with Pillow, passing the path as pathlib.Path: `from PIL import Image; from pathlib import Path; Image.open(Path("test.tiff")).tobytes()` ### What did you expect to happen? The image is correctly loaded (the same as `Image.open("test.tiff").tobytes()`; using a pathlib.Path also works just fine on Linux). ### What actually happened? ``` Traceback (most recent call last): File "<string>", line 1, in <module> File "...\Miniconda3\lib\site-packages\PIL\Image.py", line 746, in tobytes self.load() File "...\Miniconda3\lib\site-packages\PIL\TiffImagePlugin.py", line 1078, in load return super(TiffImageFile, self).load() File "...\Miniconda3\lib\site-packages\PIL\ImageFile.py", line 177, in load self.map = Image.core.map(self.filename) TypeError: argument 1 must be str, not WindowsPath ``` ### What are your OS, Python and Pillow versions? * OS: Windows 10 * Python: 3.7 * Pillow: 6.0.0
I wasn't able to replicate this on AppVeyor. I don't suppose you could say if you're only experiencing this on Windows 10, and not Windows 7? Also, while you would think this should be easy to reproduce in the right environment, could you provide a script from start to end, attaching a file if necessary, without matplotlib? ```python from pathlib import Path from PIL import Image Image.new("RGBA", (100, 100)).save("test.tiff") Image.open(Path("test.tiff")).tobytes() ``` reproes the bug for me. I don't have readily access to a win7 machine with python. This Pillow install is from PyPI, fwiw. Thanks. I've created PR #3825 to resolve this.
2019-05-04T04:17:41Z
6
python-pillow/Pillow
3,778
python-pillow__Pillow-3778
[ "3758" ]
32d10505a30207a81bb9536d46bd12ec1e7b191f
diff --git a/src/PIL/ImageSequence.py b/src/PIL/ImageSequence.py --- a/src/PIL/ImageSequence.py +++ b/src/PIL/ImageSequence.py @@ -54,3 +54,25 @@ def __next__(self): def next(self): return self.__next__() + + +def all_frames(im, func=None): + """ + Applies a given function to all frames in an image or a list of images. + The frames are returned as a list of separate images. + + :param im: An image, or a list of images. + :param func: The function to apply to all of the image frames. + :returns: A list of images. + """ + if not isinstance(im, list): + im = [im] + + ims = [] + for imSequence in im: + current = imSequence.tell() + + ims += [im_frame.copy() for im_frame in Iterator(imSequence)] + + imSequence.seek(current) + return [func(im) for im in ims] if func else ims
diff --git a/Tests/test_imagesequence.py b/Tests/test_imagesequence.py --- a/Tests/test_imagesequence.py +++ b/Tests/test_imagesequence.py @@ -74,3 +74,25 @@ def test_palette_mmap(self): im.seek(0) color2 = im.getpalette()[0:3] self.assertEqual(color1, color2) + + def test_all_frames(self): + # Test a single image + im = Image.open("Tests/images/iss634.gif") + ims = ImageSequence.all_frames(im) + + self.assertEqual(len(ims), 42) + for i, im_frame in enumerate(ims): + self.assertFalse(im_frame is im) + + im.seek(i) + self.assert_image_equal(im, im_frame) + + # Test a series of images + ims = ImageSequence.all_frames([im, hopper(), im]) + self.assertEqual(len(ims), 85) + + # Test an operation + ims = ImageSequence.all_frames(im, lambda im_frame: im_frame.rotate(90)) + for i, im_frame in enumerate(ims): + im.seek(i) + self.assert_image_equal(im.rotate(90), im_frame)
Transforms and enhancements across all frames It would be nice if transforms and enhancements could be applied on animations.
What sort of transforms and enhancements? for example. https://pillow.readthedocs.io/en/stable/handbook/tutorial.html#geometrical-transforms https://pillow.readthedocs.io/en/stable/handbook/tutorial.html#image-enhancement So when you say that you'd like them to be applied on animations, what you mean is that you'd like to be able to apply them across all frames of an image at once? yes. It seems to me that a lot of application would want a functionality like that. Okay. What about a generic way to apply a method to all frames of an image? So, for example - ```python from PIL import Image, ImageSequence im = Image.open('Tests/images/g4-multi.tiff') ims = ImageSequence.all_frames(im, lambda im_frame: im_frame.rotate(180)) ims[0].save('out.tiff', save_all=True, append_images=ims[1:]) ``` I've created this in PR #3778 lol, i was expecting a solution to this in....~5-10 years XD @radarhere is that good 😄
2019-04-08T03:25:12Z
6
python-pillow/Pillow
3,673
python-pillow__Pillow-3673
[ "3659" ]
d167f9e0bd8a71f7d0a5a1098dc9d51eceb67be2
diff --git a/src/PIL/DdsImagePlugin.py b/src/PIL/DdsImagePlugin.py --- a/src/PIL/DdsImagePlugin.py +++ b/src/PIL/DdsImagePlugin.py @@ -123,43 +123,52 @@ def _open(self): # pixel format pfsize, pfflags = struct.unpack("<2I", header.read(8)) fourcc = header.read(4) - bitcount, rmask, gmask, bmask, amask = struct.unpack("<5I", - header.read(20)) - - data_start = header_size + 4 - n = 0 - if fourcc == b"DXT1": - self.pixel_format = "DXT1" - n = 1 - elif fourcc == b"DXT3": - self.pixel_format = "DXT3" - n = 2 - elif fourcc == b"DXT5": - self.pixel_format = "DXT5" - n = 3 - elif fourcc == b"DX10": - data_start += 20 - # ignoring flags which pertain to volume textures and cubemaps - dxt10 = BytesIO(self.fp.read(20)) - dxgi_format, dimension = struct.unpack("<II", dxt10.read(8)) - if dxgi_format in (DXGI_FORMAT_BC7_TYPELESS, - DXGI_FORMAT_BC7_UNORM): - self.pixel_format = "BC7" - n = 7 - elif dxgi_format == DXGI_FORMAT_BC7_UNORM_SRGB: - self.pixel_format = "BC7" - self.im_info["gamma"] = 1/2.2 - n = 7 - else: - raise NotImplementedError("Unimplemented DXGI format %d" % - (dxgi_format)) + bitcount, = struct.unpack("<I", header.read(4)) + masks = struct.unpack("<4I", header.read(16)) + if pfflags & 0x40: + # DDPF_RGB - Texture contains uncompressed RGB data + masks = {mask: ["R", "G", "B", "A"][i] for i, mask in enumerate(masks)} + rawmode = "" + if bitcount == 32: + rawmode += masks[0xff000000] + rawmode += masks[0xff0000] + masks[0xff00] + masks[0xff] + + self.tile = [("raw", (0, 0) + self.size, 0, (rawmode, 0, 1))] else: - raise NotImplementedError("Unimplemented pixel format %r" % - (fourcc)) + data_start = header_size + 4 + n = 0 + if fourcc == b"DXT1": + self.pixel_format = "DXT1" + n = 1 + elif fourcc == b"DXT3": + self.pixel_format = "DXT3" + n = 2 + elif fourcc == b"DXT5": + self.pixel_format = "DXT5" + n = 3 + elif fourcc == b"DX10": + data_start += 20 + # ignoring flags which pertain to volume textures and cubemaps + dxt10 = BytesIO(self.fp.read(20)) + dxgi_format, dimension = struct.unpack("<II", dxt10.read(8)) + if dxgi_format in (DXGI_FORMAT_BC7_TYPELESS, + DXGI_FORMAT_BC7_UNORM): + self.pixel_format = "BC7" + n = 7 + elif dxgi_format == DXGI_FORMAT_BC7_UNORM_SRGB: + self.pixel_format = "BC7" + self.im_info["gamma"] = 1/2.2 + n = 7 + else: + raise NotImplementedError("Unimplemented DXGI format %d" % + (dxgi_format)) + else: + raise NotImplementedError("Unimplemented pixel format %r" % + (fourcc)) - self.tile = [ - ("bcn", (0, 0) + self.size, data_start, (n)) - ] + self.tile = [ + ("bcn", (0, 0) + self.size, data_start, (n)) + ] def load_seek(self, pos): pass
diff --git a/Tests/images/uncompressed_rgb.dds b/Tests/images/uncompressed_rgb.dds new file mode 100755 Binary files /dev/null and b/Tests/images/uncompressed_rgb.dds differ diff --git a/Tests/images/uncompressed_rgb.png b/Tests/images/uncompressed_rgb.png new file mode 100644 Binary files /dev/null and b/Tests/images/uncompressed_rgb.png differ diff --git a/Tests/images/unimplemented_dxgi_format.dds b/Tests/images/unimplemented_dxgi_format.dds new file mode 100644 Binary files /dev/null and b/Tests/images/unimplemented_dxgi_format.dds differ diff --git a/Tests/images/unimplemented_pixel_format.dds b/Tests/images/unimplemented_pixel_format.dds new file mode 100755 Binary files /dev/null and b/Tests/images/unimplemented_pixel_format.dds differ diff --git a/Tests/test_file_dds.py b/Tests/test_file_dds.py --- a/Tests/test_file_dds.py +++ b/Tests/test_file_dds.py @@ -7,6 +7,7 @@ TEST_FILE_DXT3 = "Tests/images/dxt3-argb-8bbp-explicitalpha_MipMaps-1.dds" TEST_FILE_DXT5 = "Tests/images/dxt5-argb-8bbp-interpolatedalpha_MipMaps-1.dds" TEST_FILE_DX10_BC7 = "Tests/images/bc7-argb-8bpp_MipMaps-1.dds" +TEST_FILE_UNCOMPRESSED_RGB = "Tests/images/uncompressed_rgb.dds" class TestFileDds(PillowTestCase): @@ -67,6 +68,24 @@ def test_dx10_bc7(self): self.assert_image_equal(target, im) + def test_unimplemented_dxgi_format(self): + self.assertRaises(NotImplementedError, Image.open, + "Tests/images/unimplemented_dxgi_format.dds") + + def test_uncompressed_rgb(self): + """Check uncompressed RGB images can be opened""" + + target = Image.open(TEST_FILE_UNCOMPRESSED_RGB.replace('.dds', '.png')) + + im = Image.open(TEST_FILE_UNCOMPRESSED_RGB) + im.load() + + self.assertEqual(im.format, "DDS") + self.assertEqual(im.mode, "RGBA") + self.assertEqual(im.size, (800, 600)) + + self.assert_image_equal(target, im) + def test__validate_true(self): """Check valid prefix""" # Arrange @@ -110,3 +129,7 @@ def short_file(): im.load() self.assertRaises(IOError, short_file) + + def test_unimplemented_pixel_format(self): + self.assertRaises(NotImplementedError, Image.open, + "Tests/images/unimplemented_pixel_format.dds")
DDS Plugin cannot handle uncompressed files Loading a DDS file without compression gives me the following error: ``` File "<SNIP>\PIL\Image.py", line 2676, in open im = _open_core(fp, filename, prefix) File "<SNIP>\PIL\Image.py", line 2658, in _open_core im = factory(fp, filename) File "<SNIP>\PIL\ImageFile.py", line 103, in __init__ self._open() File "<SNIP>\PIL\DdsImagePlugin.py", line 158, in _open (fourcc)) NotImplementedError: Unimplemented pixel format b'\x00\x00\x00\x00' ``` To demonstrate the issue, I created a simple DDS file as demonstration. Calling `Image.open()` on that file will not work. [uncompressed_dds.zip](https://github.com/python-pillow/Pillow/files/2872238/uncompressed_dds.zip) Looking over the source code of DdsImagePlugin, it seems that only FourCC DDS files are supported. Pillow version: 5.4.1 Python version: 3.7.2
The docs say only DXT1, DXT3 and DXT5 in `RGBA`: > DDS is a popular container texture format used in video games and natively supported by DirectX. Currently, DXT1, DXT3, and DXT5 pixel formats are supported and only in `RGBA` mode. https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html?highlight=dds#dds The code also includes three DXGI formats of DXT10: https://github.com/python-pillow/Pillow/blob/daa8b5133923561d2c6d4d1f7b2c9d9aa233007e/src/PIL/DdsImagePlugin.py#L131-L158 Ah, I hadn't seen the documentation. Let's turn this into a feature request, then. @Xfel is the file that you have provided able to added to the test suite under the Pillow license? I created this file specifically for this demonstration, so it should be fine. (it's just a bunch of random scribbles anyways).
2019-02-22T19:45:09Z
5.4
python-pillow/Pillow
3,625
python-pillow__Pillow-3625
[ "520", "2081" ]
ed596499ecf22d1ccbcacc5a818c7659a92a6334
diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py --- a/src/PIL/ImageFile.py +++ b/src/PIL/ImageFile.py @@ -27,11 +27,20 @@ # See the README file for information on usage and redistribution. # -from . import Image -from ._util import isPath +from . import Image, TiffTags +from ._binary import i32le +from ._util import isPath, py3 import io import sys import struct +import warnings + +try: + # Python 3 + from collections.abc import MutableMapping +except ImportError: + # Python 2.7 + from collections import MutableMapping MAXBLOCK = 65536 @@ -293,6 +302,12 @@ def _seek_check(self, frame): return self.tell() != frame + def getexif(self): + exif = Exif() + if "exif" in self.info: + exif.load(self.info["exif"]) + return exif + class StubImageFile(ImageFile): """ @@ -672,3 +687,182 @@ def set_as_raw(self, data, rawmode=None): raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") + + +class Exif(MutableMapping): + endian = "<" + + def __init__(self): + self._data = {} + self._ifds = {} + + def _fixup_dict(self, src_dict): + # Helper function for _getexif() + # returns a dict with any single item tuples/lists as individual values + def _fixup(value): + try: + if len(value) == 1 and not isinstance(value, dict): + return value[0] + except Exception: + pass + return value + + return {k: _fixup(v) for k, v in src_dict.items()} + + def _get_ifd_dict(self, tag): + try: + # an offset pointer to the location of the nested embedded IFD. + # It should be a long, but may be corrupted. + self.fp.seek(self._data[tag]) + except (KeyError, TypeError): + pass + else: + from . import TiffImagePlugin + info = TiffImagePlugin.ImageFileDirectory_v1(self.head) + info.load(self.fp) + return self._fixup_dict(info) + + def load(self, data): + # Extract EXIF information. This is highly experimental, + # and is likely to be replaced with something better in a future + # version. + + # The EXIF record consists of a TIFF file embedded in a JPEG + # application marker (!). + self.fp = io.BytesIO(data[6:]) + self.head = self.fp.read(8) + # process dictionary + from . import TiffImagePlugin + info = TiffImagePlugin.ImageFileDirectory_v1(self.head) + self.endian = info._endian + self.fp.seek(info.next) + info.load(self.fp) + self._data = dict(self._fixup_dict(info)) + + # get EXIF extension + ifd = self._get_ifd_dict(0x8769) + if ifd: + self._data.update(ifd) + self._ifds[0x8769] = ifd + + # get gpsinfo extension + ifd = self._get_ifd_dict(0x8825) + if ifd: + self._data[0x8825] = ifd + self._ifds[0x8825] = ifd + + def tobytes(self, offset=0): + from . import TiffImagePlugin + if self.endian == "<": + head = b"II\x2A\x00\x08\x00\x00\x00" + else: + head = b"MM\x00\x2A\x00\x00\x00\x08" + ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head) + for tag, value in self._data.items(): + ifd[tag] = value + return b"Exif\x00\x00"+head+ifd.tobytes(offset) + + def get_ifd(self, tag): + if tag not in self._ifds and tag in self._data: + if tag == 0xa005: # interop + self._ifds[tag] = self._get_ifd_dict(tag) + elif tag == 0x927c: # makernote + from . import TiffImagePlugin + if self._data[0x927c][:8] == b"FUJIFILM": + exif_data = self._data[0x927c] + ifd_offset = i32le(exif_data[8:12]) + ifd_data = exif_data[ifd_offset:] + + makernote = {} + for i in range(0, struct.unpack("<H", ifd_data[:2])[0]): + ifd_tag, typ, count, data = struct.unpack( + "<HHL4s", ifd_data[i*12 + 2:(i+1)*12 + 2]) + try: + unit_size, handler =\ + TiffImagePlugin.ImageFileDirectory_v2._load_dispatch[ + typ + ] + except KeyError: + continue + size = count * unit_size + if size > 4: + offset, = struct.unpack("<L", data) + data = ifd_data[offset-12:offset+size-12] + else: + data = data[:size] + + if len(data) != size: + warnings.warn("Possibly corrupt EXIF MakerNote data. " + "Expecting to read %d bytes but only got %d." + " Skipping tag %s" + % (size, len(data), ifd_tag)) + continue + + if not data: + continue + + makernote[ifd_tag] = handler( + TiffImagePlugin.ImageFileDirectory_v2(), data, False) + self._ifds[0x927c] = dict(self._fixup_dict(makernote)) + elif self._data.get(0x010f) == "Nintendo": + ifd_data = self._data[0x927c] + + makernote = {} + for i in range(0, struct.unpack(">H", ifd_data[:2])[0]): + ifd_tag, typ, count, data = struct.unpack( + ">HHL4s", ifd_data[i*12 + 2:(i+1)*12 + 2]) + if ifd_tag == 0x1101: + # CameraInfo + offset, = struct.unpack(">L", data) + self.fp.seek(offset) + + camerainfo = {'ModelID': self.fp.read(4)} + + self.fp.read(4) + # Seconds since 2000 + camerainfo['TimeStamp'] = i32le(self.fp.read(12)) + + self.fp.read(4) + camerainfo['InternalSerialNumber'] = self.fp.read(4) + + self.fp.read(12) + parallax = self.fp.read(4) + handler =\ + TiffImagePlugin.ImageFileDirectory_v2._load_dispatch[ + TiffTags.FLOAT + ][1] + camerainfo['Parallax'] = handler( + TiffImagePlugin.ImageFileDirectory_v2(), + parallax, False) + + self.fp.read(4) + camerainfo['Category'] = self.fp.read(2) + + makernote = {0x1101: dict(self._fixup_dict(camerainfo))} + self._ifds[0x927c] = makernote + return self._ifds.get(tag, {}) + + def __str__(self): + return str(self._data) + + def __len__(self): + return len(self._data) + + def __getitem__(self, tag): + return self._data[tag] + + def __contains__(self, tag): + return tag in self._data + + if not py3: + def has_key(self, tag): + return tag in self + + def __setitem__(self, tag, value): + self._data[tag] = value + + def __delitem__(self, tag): + del self._data[tag] + + def __iter__(self): + return iter(set(self._data)) diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py --- a/src/PIL/JpegImagePlugin.py +++ b/src/PIL/JpegImagePlugin.py @@ -86,7 +86,7 @@ def APP(self, marker): self.info["jfif_density"] = jfif_density elif marker == 0xFFE1 and s[:5] == b"Exif\0": if "exif" not in self.info: - # extract Exif information (incomplete) + # extract EXIF information (incomplete) self.info["exif"] = s # FIXME: value will change elif marker == 0xFFE2 and s[:5] == b"FPXR\0": # extract FlashPix information (incomplete) @@ -168,7 +168,7 @@ def APP(self, marker): dpi *= 2.54 self.info["dpi"] = dpi, dpi except (KeyError, SyntaxError, ZeroDivisionError): - # SyntaxError for invalid/unreadable exif + # SyntaxError for invalid/unreadable EXIF # KeyError for dpi not included # ZeroDivisionError for invalid dpi rational value self.info["dpi"] = 72, 72 @@ -472,65 +472,20 @@ def _getmp(self): def _fixup_dict(src_dict): # Helper function for _getexif() # returns a dict with any single item tuples/lists as individual values - def _fixup(value): - try: - if len(value) == 1 and not isinstance(value, dict): - return value[0] - except Exception: - pass - return value - - return {k: _fixup(v) for k, v in src_dict.items()} + exif = ImageFile.Exif() + return exif._fixup_dict(src_dict) def _getexif(self): - # Extract EXIF information. This method is highly experimental, - # and is likely to be replaced with something better in a future - # version. - # Use the cached version if possible try: return self.info["parsed_exif"] except KeyError: pass - # The EXIF record consists of a TIFF file embedded in a JPEG - # application marker (!). - try: - data = self.info["exif"] - except KeyError: + if "exif" not in self.info: return None - fp = io.BytesIO(data[6:]) - head = fp.read(8) - # process dictionary - info = TiffImagePlugin.ImageFileDirectory_v1(head) - fp.seek(info.next) - info.load(fp) - exif = dict(_fixup_dict(info)) - # get exif extension - try: - # exif field 0x8769 is an offset pointer to the location - # of the nested embedded exif ifd. - # It should be a long, but may be corrupted. - fp.seek(exif[0x8769]) - except (KeyError, TypeError): - pass - else: - info = TiffImagePlugin.ImageFileDirectory_v1(head) - info.load(fp) - exif.update(_fixup_dict(info)) - # get gpsinfo extension - try: - # exif field 0x8825 is an offset pointer to the location - # of the nested embedded gps exif ifd. - # It should be a long, but may be corrupted. - fp.seek(exif[0x8825]) - except (KeyError, TypeError): - pass - else: - info = TiffImagePlugin.ImageFileDirectory_v1(head) - info.load(fp) - exif[0x8825] = _fixup_dict(info) + exif = dict(self.getexif()) # Cache the result for future use self.info["parsed_exif"] = exif @@ -769,6 +724,10 @@ def validate_qtables(qtables): optimize = info.get("optimize", False) + exif = info.get("exif", b"") + if isinstance(exif, ImageFile.Exif): + exif = exif.tobytes() + # get keyword arguments im.encoderconfig = ( quality, @@ -780,7 +739,7 @@ def validate_qtables(qtables): subsampling, qtables, extra, - info.get("exif", b"") + exif ) # if we optimize, libjpeg needs a buffer big enough to hold the whole image @@ -798,9 +757,9 @@ def validate_qtables(qtables): else: bufsize = im.size[0] * im.size[1] - # The exif info needs to be written as one block, + APP1, + one spare byte. + # The EXIF info needs to be written as one block, + APP1, + one spare byte. # Ensure that our buffer is big enough. Same with the icc_profile block. - bufsize = max(ImageFile.MAXBLOCK, bufsize, len(info.get("exif", b"")) + 5, + bufsize = max(ImageFile.MAXBLOCK, bufsize, len(exif) + 5, len(extra) + 1) ImageFile._save(im, fp, [("jpeg", (0, 0)+im.size, 0, rawmode)], bufsize) diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -696,8 +696,14 @@ def load_end(self): def _getexif(self): if "exif" not in self.info: self.load() - from .JpegImagePlugin import _getexif - return _getexif(self) + if "exif" not in self.info: + return None + return dict(self.getexif()) + + def getexif(self): + if "exif" not in self.info: + self.load() + return ImageFile.ImageFile.getexif(self) # -------------------------------------------------------------------- @@ -880,6 +886,8 @@ def _save(im, fp, filename, chunk=putchunk): exif = im.encoderinfo.get("exif", im.info.get("exif")) if exif: + if isinstance(exif, ImageFile.Exif): + exif = exif.tobytes(8) if exif.startswith(b"Exif\x00\x00"): exif = exif[6:] chunk(fp, b"eXIf", exif) diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -785,17 +785,12 @@ def load(self, fp): warnings.warn(str(msg)) return - def save(self, fp): - - if fp.tell() == 0: # skip TIFF header on subsequent pages - # tiff header -- PIL always starts the first IFD at offset 8 - fp.write(self._prefix + self._pack("HL", 42, 8)) - + def tobytes(self, offset=0): # FIXME What about tagdata? - fp.write(self._pack("H", len(self._tags_v2))) + result = self._pack("H", len(self._tags_v2)) entries = [] - offset = fp.tell() + len(self._tags_v2) * 12 + 4 + offset = offset + len(result) + len(self._tags_v2) * 12 + 4 stripoffsets = None # pass 1: convert tags to binary format @@ -844,18 +839,29 @@ def save(self, fp): for tag, typ, count, value, data in entries: if DEBUG > 1: print(tag, typ, count, repr(value), repr(data)) - fp.write(self._pack("HHL4s", tag, typ, count, value)) + result += self._pack("HHL4s", tag, typ, count, value) # -- overwrite here for multi-page -- - fp.write(b"\0\0\0\0") # end of entries + result += b"\0\0\0\0" # end of entries # pass 3: write auxiliary data to file for tag, typ, count, value, data in entries: - fp.write(data) + result += data if len(data) & 1: - fp.write(b"\0") + result += b"\0" + + return result + + def save(self, fp): + + if fp.tell() == 0: # skip TIFF header on subsequent pages + # tiff header -- PIL always starts the first IFD at offset 8 + fp.write(self._prefix + self._pack("HL", 42, 8)) - return offset + offset = fp.tell() + result = self.tobytes(offset) + fp.write(result) + return offset + len(result) ImageFileDirectory_v2._load_dispatch = _load_dispatch diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py --- a/src/PIL/WebPImagePlugin.py +++ b/src/PIL/WebPImagePlugin.py @@ -93,8 +93,9 @@ def _open(self): self.seek(0) def _getexif(self): - from .JpegImagePlugin import _getexif - return _getexif(self) + if "exif" not in self.info: + return None + return dict(self.getexif()) @property def n_frames(self): @@ -216,6 +217,8 @@ def _save_all(im, fp, filename): method = im.encoderinfo.get("method", 0) icc_profile = im.encoderinfo.get("icc_profile", "") exif = im.encoderinfo.get("exif", "") + if isinstance(exif, ImageFile.Exif): + exif = exif.tobytes() xmp = im.encoderinfo.get("xmp", "") if allow_mixed: lossless = False @@ -315,6 +318,8 @@ def _save(im, fp, filename): quality = im.encoderinfo.get("quality", 80) icc_profile = im.encoderinfo.get("icc_profile", "") exif = im.encoderinfo.get("exif", "") + if isinstance(exif, ImageFile.Exif): + exif = exif.tobytes() xmp = im.encoderinfo.get("xmp", "") if im.mode not in _VALID_WEBP_LEGACY_MODES:
diff --git a/Tests/images/fujifilm.mpo b/Tests/images/fujifilm.mpo new file mode 100644 Binary files /dev/null and b/Tests/images/fujifilm.mpo differ diff --git a/Tests/test_file_mpo.py b/Tests/test_file_mpo.py --- a/Tests/test_file_mpo.py +++ b/Tests/test_file_mpo.py @@ -64,6 +64,18 @@ def test_frame_size(self): im.seek(1) self.assertEqual(im.size, (680, 480)) + def test_parallax(self): + # Nintendo + im = Image.open("Tests/images/sugarshack.mpo") + exif = im.getexif() + self.assertEqual(exif.get_ifd(0x927c)[0x1101]["Parallax"], -44.798187255859375) + + # Fujifilm + im = Image.open("Tests/images/fujifilm.mpo") + im.seek(1) + exif = im.getexif() + self.assertEqual(exif.get_ifd(0x927c)[0xb211], -3.125) + def test_mp(self): for test_file in test_files: im = Image.open(test_file) diff --git a/Tests/test_imagefile.py b/Tests/test_imagefile.py --- a/Tests/test_imagefile.py +++ b/Tests/test_imagefile.py @@ -1,4 +1,4 @@ -from .helper import PillowTestCase, hopper, fromstring, tostring +from .helper import unittest, PillowTestCase, hopper, fromstring, tostring from io import BytesIO @@ -6,6 +6,12 @@ from PIL import ImageFile from PIL import EpsImagePlugin +try: + from PIL import _webp + HAVE_WEBP = True +except ImportError: + HAVE_WEBP = False + codecs = dir(Image.core) @@ -233,3 +239,97 @@ def test_no_format(self): im = MockImageFile(buf) self.assertIsNone(im.format) self.assertIsNone(im.get_format_mimetype()) + + def test_exif_jpeg(self): + im = Image.open("Tests/images/exif-72dpi-int.jpg") # Little endian + exif = im.getexif() + self.assertNotIn(258, exif) + self.assertIn(40960, exif) + self.assertEqual(exif[40963], 450) + self.assertEqual(exif[11], "gThumb 3.0.1") + + out = self.tempfile('temp.jpg') + exif[258] = 8 + del exif[40960] + exif[40963] = 455 + exif[11] = "Pillow test" + im.save(out, exif=exif) + reloaded = Image.open(out) + reloaded_exif = reloaded.getexif() + self.assertEqual(reloaded_exif[258], 8) + self.assertNotIn(40960, exif) + self.assertEqual(reloaded_exif[40963], 455) + self.assertEqual(exif[11], "Pillow test") + + im = Image.open("Tests/images/no-dpi-in-exif.jpg") # Big endian + exif = im.getexif() + self.assertNotIn(258, exif) + self.assertIn(40962, exif) + self.assertEqual(exif[40963], 200) + self.assertEqual(exif[305], "Adobe Photoshop CC 2017 (Macintosh)") + + out = self.tempfile('temp.jpg') + exif[258] = 8 + del exif[34665] + exif[40963] = 455 + exif[305] = "Pillow test" + im.save(out, exif=exif) + reloaded = Image.open(out) + reloaded_exif = reloaded.getexif() + self.assertEqual(reloaded_exif[258], 8) + self.assertNotIn(40960, exif) + self.assertEqual(reloaded_exif[40963], 455) + self.assertEqual(exif[305], "Pillow test") + + @unittest.skipIf(not HAVE_WEBP or not _webp.HAVE_WEBPANIM, + "WebP support not installed with animation") + def test_exif_webp(self): + im = Image.open("Tests/images/hopper.webp") + exif = im.getexif() + self.assertEqual(exif, {}) + + out = self.tempfile('temp.webp') + exif[258] = 8 + exif[40963] = 455 + exif[305] = "Pillow test" + + def check_exif(): + reloaded = Image.open(out) + reloaded_exif = reloaded.getexif() + self.assertEqual(reloaded_exif[258], 8) + self.assertEqual(reloaded_exif[40963], 455) + self.assertEqual(exif[305], "Pillow test") + im.save(out, exif=exif) + check_exif() + im.save(out, exif=exif, save_all=True) + check_exif() + + def test_exif_png(self): + im = Image.open("Tests/images/exif.png") + exif = im.getexif() + self.assertEqual(exif, {274: 1}) + + out = self.tempfile('temp.png') + exif[258] = 8 + del exif[274] + exif[40963] = 455 + exif[305] = "Pillow test" + im.save(out, exif=exif) + + reloaded = Image.open(out) + reloaded_exif = reloaded.getexif() + self.assertEqual(reloaded_exif, { + 258: 8, + 40963: 455, + 305: 'Pillow test', + }) + + def test_exif_interop(self): + im = Image.open("Tests/images/flower.jpg") + exif = im.getexif() + self.assertEqual(exif.get_ifd(0xa005), { + 1: 'R98', + 2: b'0100', + 4097: 2272, + 4098: 1704, + })
Make EXIF plugin Exif support (labeled experimental since 2003) is somewhat adequate for reading, but there's no clear way to change a value and then write it out. We currently support writing Exif as byte strings, with no way to make them apart from manually setting up nested `TiffImagePlugin.ImageFileDirectory` instances, then calling save into a file pointer. - `Image.getexif()` should exist, and return an Exif object. - The Exif object should export a dictionary interface. - The Exif object should have a `toBytes()` method returning the correct bytes. - `Exif.load(bytes).toBytes()` should roundtrip. - This should work: ```python exif = Exif() exif['Orientation'] = 1 im.save('temp.jpg', exif=exif) ``` No way to read Parallax tag from stereo MPO files Stereo MPO files (such as those produced with the Fujifilm Finepix W3 camera) store the parallax value in a tag in the EXIF information of the _second_ image in the MPO file, but it appears that Pillow can only read the EXIF information from the first image at present. The tag can be manually read via exiftool as follows: ``` bash $ exiftool DSCF3195.MPO -mpimage2 -b > DSCF3195-r.jpg $ exiftool DSCF3195-r.jpg -Parallax Parallax : 5.625 ``` I have several sample MPO files available: http://valen.darkstarsword.net/photos/stereo/misc/originals/ I would like to make use of this tag in my Stereo Cropping Tool ( https://github.com/DarkStarSword/StereoCropper ) to start with the correct parallax value.
Can the EXIF tags (or any metadata) be preserved when resizing or generating thumbnails? I wrote a Exif class, that is subclass of dict. Methods "to_bytes" and "load" are added. How is this for prototype? https://github.com/hMatoba/EXIF Thanks. I'll take a look, probably after we get 2.6.0 out I noticed the bump to 2.7.0, so any thought to this bug? It didn't get worked on. There is some action on dealing with tiff IFDs in #1059, so something may still come of it. (Though, that PR needs to be worked on due to incompatibilities with existing code) We're now in version 3+, I wonder if this has this been touched? No, but there have been some underlying changes to the tiff ifd code that may lead to motion. It certainly needs to be done. Trying to understand, can anyone explain to me what the purpose of a `toBytes()` method is? I mean, it's not so that it can be passed back into Pillow, since this new class could do that itself, and it's not for humans to read. Is it so that the value can be stored for later use? Is it so that the value can be used in another program? I've created PR #3625 to resolve this. > Trying to understand, can anyone explain to me what the purpose of a `toBytes()` method is? I mean, it's not so that it can be passed back into Pillow, since this new class could do that itself, and it's not for humans to read. Is it so that the value can be stored for later use? Is it so that the value can be used in another program? I would assume being able to load them in another package like `piexif` is what would make the most sense. Although, I believe you can just do `piexif.load(image.info['exif'])` which bypasses the need for `toBytes()` here, correct? I can't seem to get the image size of the second frame. Did you ever figure this out? I'm trying to split mpo files but can't crop the second frame without knowing its size. And doing a seek then save just saves the second frame at the size of the first frame I haven't looked into it further... it only represents a relatively small enhancement for my tool since my tool is designed to allow the user to very rapidly adjust the parallax and crop on a stereo photo, so not having the parallax pre-set only equates to maybe a second or two of inconvenience per photo... Still, it would be nice to have. BTW - this is unrelated to Pillow, but I have a shell script that can convert .mpo files into various other formats (including .jps) and correctly accounts for the parallax tag: https://github.com/DarkStarSword/3d-fixes/blob/master/photo-gallery/orig2all.sh Are there any images that could be included as part of the test suite, under Pillow's license? #3625 has commits to resolve this. A problem here is that the parallax data is stored in the MakerNote tag - this is specific to the manufacturer. So in the PR, I have added reading of the Fujifilm format that you provide here, and the Nintendo format that is already in our test suite. If there are any other formats that you would like supported, please let us know. > Are there any images that could be included as part of the test suite, under Pillow's license? Feel free to take your pick from any of these - they're all my own work and I'm more than happy for them to be used under Pillow's license: http://valen.darkstarsword.net/photos/stereo/misc/originals/ Thanks very much! I've added one of the images to the PR. Thanks for the image! However, it's nearly 10 MB, and our current source zip (including most test images) is 16 MB. Would it be possible to create one which is, say, less than a megabyte? If not, shall we leave it out of this repo (and the source zip) and put it in https://github.com/python-pillow/pillow-depends/tree/master/test_images instead, and pull it in just for testing? Just for the record - while a natural image is obviously better, another option would be to switch back to original 117kb file from my original commits in the PR. I copied one of the existing test images and then manually hexedited in the parallax data.
2019-01-31T14:40:54Z
5.4
python-pillow/Pillow
3,588
python-pillow__Pillow-3588
[ "1631" ]
0306b80ef78aa8ab9f36f62cf2b8f21c3145e3d3
diff --git a/src/PIL/MpoImagePlugin.py b/src/PIL/MpoImagePlugin.py --- a/src/PIL/MpoImagePlugin.py +++ b/src/PIL/MpoImagePlugin.py @@ -18,7 +18,8 @@ # See the README file for information on usage and redistribution. # -from . import Image, JpegImagePlugin +from . import Image, ImageFile, JpegImagePlugin +from ._binary import i16be as i16 # __version__ is deprecated and will be removed in a future version. Use # PIL.__version__ instead. @@ -78,6 +79,20 @@ def seek(self, frame): return self.fp = self.__fp self.offset = self.__mpoffsets[frame] + + self.fp.seek(self.offset + 2) # skip SOI marker + if "parsed_exif" in self.info: + del self.info["parsed_exif"] + if i16(self.fp.read(2)) == 0xFFE1: # APP1 + n = i16(self.fp.read(2))-2 + self.info["exif"] = ImageFile._safe_read(self.fp, n) + + exif = self._getexif() + if 40962 in exif and 40963 in exif: + self._size = (exif[40962], exif[40963]) + elif "exif" in self.info: + del self.info["exif"] + self.tile = [ ("jpeg", (0, 0) + self.size, self.offset, (self.mode, "")) ]
diff --git a/Tests/images/sugarshack_frame_size.mpo b/Tests/images/sugarshack_frame_size.mpo new file mode 100644 Binary files /dev/null and b/Tests/images/sugarshack_frame_size.mpo differ diff --git a/Tests/test_file_mpo.py b/Tests/test_file_mpo.py --- a/Tests/test_file_mpo.py +++ b/Tests/test_file_mpo.py @@ -55,6 +55,15 @@ def test_exif(self): self.assertEqual(info[296], 2) self.assertEqual(info[34665], 188) + def test_frame_size(self): + # This image has been hexedited to contain a different size + # in the EXIF data of the second frame + im = Image.open("Tests/images/sugarshack_frame_size.mpo") + self.assertEqual(im.size, (640, 480)) + + im.seek(1) + self.assertEqual(im.size, (680, 480)) + def test_mp(self): for test_file in test_files: im = Image.open(test_file)
No n_frames, or bad value for n_frames When I feed the test file flower2.jpg into this code (from #1630) ```python im = Image.open( fn ) imgcnt = im.n_frames colors = im.getcolors( im.width * im.height ) if args.hist: for cnt, col in colors: allcolors[ col ] += cnt for iz in range( 1, imgcnt ): im = Image.open( fn ) # does getcolors implicitly close???? # without the open, get "seek of closed # file" error on line below. im.seek( iz ) colors = im.getcolors( im.width * im.height ) for cnt, col in colors: allcolors[ col ] += cnt ``` I get "AttributeError: n_frames" But other .jpg files do not get that error... this one: http://nevcal.com/temporary/20151110-105826gl.jpg has no problem with the attribute error on that line, but it gets a value of 2, apparently handles the seek OK, but dies in the second call to getcolors, with "OSError: image file is truncated (0 bytes not processed)".
I'd expect .jpg files to always return 1 as the n_frames attribute; some from some cameras have an embedded thumbnail in the metadata, but I don't think that is particularly standard? Same environment as for #1630: Windows 10, Python 3.5.0, Pillow 3.0.0. So I've added a hasattr workaround to avoid the Attribute error, but when the attribute exists, but is wrong? Harder to deal with... Hi. I think the simple answer to your question is that 20151110-105826gl.jpg is not actually a JPEG file. It's an MPO, and Pillow reads it as such, giving it an `n_frames` attribute. This is a case of the file extension not reflecting the type of file. JPEGs do not have multiple frames, and so currently don't have the `n_frames` attribute. If you think that a change should be made to Pillow to clarify this somehow, feel free to say. With regards to `OSError: image file is truncated (0 bytes not processed)`, the error can replicated with - ```python from PIL import Image im = Image.open('test.jpg') im.seek(1) im.load() ``` So it has nothing to do with n_frames. Is there any reason you think that the file isn't truncated as the error suggests? Re: no n_frames for JPEG... I thought I saw some comments here and a pull request for adding n_frames to file types that didn't have them, for uniformity. Maybe that isn't released yet. Re: MPO support. I had never heard of MPO until you mentioned them. I found a little info on Wikipedia, and my camera is listed as one that uses them. The picture is one I took with my camera. All consistent so far. I copied the file from the camera. I didn't truncate it. I don't know why the camera would. I haven't found good documentation for MPO yet, that explains what EXIF fields distinguish them from JPG. None of my other JPG software has complained about them not being JPG. This error may have nothing to do with n_frames, except that one shouldn't seek(1) if there are not n_frames, and n_frames produces 2. Thanks again for your analysis. I have some things to learn now... but there may be a bug, or at least a necessary workaround, for MPO files named JPG that come off standard consumer cameras.
2019-01-17T13:02:19Z
5.4
python-pillow/Pillow
3,532
python-pillow__Pillow-3532
[ "3527" ]
41fba67fb028807472eddb126fa228214178008d
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -677,6 +677,8 @@ def load_end(self): self.png.call(cid, pos, length) except UnicodeDecodeError: break + except EOFError: + ImageFile._safe_read(self.fp, length) self._text = self.png.im_text self.png.close() self.png = None
diff --git a/Tests/images/hopper_idat_after_image_end.png b/Tests/images/hopper_idat_after_image_end.png new file mode 100644 Binary files /dev/null and b/Tests/images/hopper_idat_after_image_end.png differ diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -585,6 +585,10 @@ def test_textual_chunks_after_idat(self): self.assertIsInstance(im.text, dict) ImageFile.LOAD_TRUNCATED_IMAGES = False + # Raises an EOFError in load_end + im = Image.open("Tests/images/hopper_idat_after_image_end.png") + self.assertEqual(im.text, {'TXT': 'VALUE', 'ZIP': 'VALUE'}) + @unittest.skipUnless(HAVE_WEBP and _webp.HAVE_WEBPANIM, "WebP support not installed with animation") def test_apng(self):
Error when loading some PNG images After update PIL to 5.4.0 I cannot load an image ![mastercard](https://user-images.githubusercontent.com/9046065/50598772-71f08100-0eb4-11e9-99cd-126e65673626.png) [_image duplicate on Google drive_](https://drive.google.com/open?id=19pwEEGBh7h1iYRn3uSC19z8tkiHokPJQ) The example code shown bellow raises `EOFError`. But it worked correctly in previous versions. The error was reproduced in Ubuntu 14.04 + Python 3.6.7 and macOS Sierra 10.12.6 + Python 3.6.3. In both cases Pillow 5.4.0 was uses. it seems the error was caused by the commit [22837c37e279a5fb3fb7b482d81e2c4d44c8cdcc](https://github.com/python-pillow/Pillow/commit/22837c37e279a5fb3fb7b482d81e2c4d44c8cdcc). ```python from io import BytesIO from PIL import Image with open('mastercard.png', mode='rb') as fp: im_bytes = fp.read() image = Image.open(BytesIO(im_bytes)) image.show() ``` Error log: ``` EOFError Traceback (most recent call last) <ipython-input-11-d946298b95dd> in <module> ----> 1 image.show() ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/Image.py in show(self, title, command) 2039 """ 2040 -> 2041 _show(self, title=title, command=command) 2042 2043 def split(self): ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/Image.py in _show(image, **options) 2904 def _show(image, **options): 2905 # override me, as necessary -> 2906 _showxv(image, **options) 2907 2908 ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/Image.py in _showxv(image, title, **options) 2909 def _showxv(image, title=None, **options): 2910 from . import ImageShow -> 2911 ImageShow.show(image, title, **options) 2912 2913 ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/ImageShow.py in show(image, title, **options) 51 """ 52 for viewer in _viewers: ---> 53 if viewer.show(image, title=title, **options): 54 return 1 55 return 0 ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/ImageShow.py in show(self, image, **options) 75 image = image.convert(base) 76 ---> 77 return self.show_image(image, **options) 78 79 # hook methods ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/ImageShow.py in show_image(self, image, **options) 95 def show_image(self, image, **options): 96 """Display given image""" ---> 97 return self.show_file(self.save_image(image), **options) 98 99 def show_file(self, file, **options): ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/ImageShow.py in save_image(self, image) 91 def save_image(self, image): 92 """Save to temporary file, and return filename""" ---> 93 return image._dump(format=self.get_format(image), **self.options) 94 95 def show_image(self, image, **options): ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/Image.py in _dump(self, file, format, **options) 646 filename = filename + suffix 647 --> 648 self.load() 649 650 if not format or format == "PPM": ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/ImageFile.py in load(self) 248 self.readonly = readonly 249 --> 250 self.load_end() 251 252 if self._exclusive_fp and self._close_exclusive_fp_after_loading: ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/PngImagePlugin.py in load_end(self) 675 676 try: --> 677 self.png.call(cid, pos, length) 678 except UnicodeDecodeError: 679 break ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/PngImagePlugin.py in call(self, cid, pos, length) 138 139 logger.debug("STREAM %r %s %s", cid, pos, length) --> 140 return getattr(self, "chunk_" + cid.decode('ascii'))(pos, length) 141 142 def crc(self, cid, data): ~/py/ocean/ocean_ai/env/lib/python3.6/site-packages/PIL/PngImagePlugin.py in chunk_IDAT(self, pos, length) 354 self.im_tile = [("zip", (0, 0)+self.im_size, pos, self.im_rawmode)] 355 self.im_idat = length --> 356 raise EOFError 357 358 def chunk_IEND(self, pos, length): EOFError: ```
Reproducible with 5.4.0 with: ```python from PIL import Image im = Image.open("mastercard.png") ``` Not reproducible with 5.3.0. @hugovk I find your comment surprising, given that the traceback involves `load()`. Would you be able to post your traceback? Sorry, missed the last line: ```python from PIL import Image im = Image.open("mastercard.png") im.show() ``` ```python Python 3.7.1 (default, Nov 6 2018, 18:45:35) [Clang 10.0.0 (clang-1000.11.45.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from PIL import Image >>> im = Image.open("mastercard.png") >>> im.show() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/hugo/github/Pillow/src/PIL/Image.py", line 2041, in show _show(self, title=title, command=command) File "/Users/hugo/github/Pillow/src/PIL/Image.py", line 2906, in _show _showxv(image, **options) File "/Users/hugo/github/Pillow/src/PIL/Image.py", line 2911, in _showxv ImageShow.show(image, title, **options) File "/Users/hugo/github/Pillow/src/PIL/ImageShow.py", line 53, in show if viewer.show(image, title=title, **options): File "/Users/hugo/github/Pillow/src/PIL/ImageShow.py", line 77, in show return self.show_image(image, **options) File "/Users/hugo/github/Pillow/src/PIL/ImageShow.py", line 97, in show_image return self.show_file(self.save_image(image), **options) File "/Users/hugo/github/Pillow/src/PIL/ImageShow.py", line 93, in save_image return image._dump(format=self.get_format(image), **self.options) File "/Users/hugo/github/Pillow/src/PIL/Image.py", line 648, in _dump self.load() File "/Users/hugo/github/Pillow/src/PIL/ImageFile.py", line 250, in load self.load_end() File "/Users/hugo/github/Pillow/src/PIL/PngImagePlugin.py", line 677, in load_end self.png.call(cid, pos, length) File "/Users/hugo/github/Pillow/src/PIL/PngImagePlugin.py", line 140, in call return getattr(self, "chunk_" + cid.decode('ascii'))(pos, length) File "/Users/hugo/github/Pillow/src/PIL/PngImagePlugin.py", line 356, in chunk_IDAT raise EOFError EOFError >>> ``` It looks like this only happen if the chunk types 'IDAT' and 'IEND' are in the file.
2019-01-03T06:29:19Z
5.4
python-pillow/Pillow
3,558
python-pillow__Pillow-3558
[ "3557" ]
7bf5246b93cc89cfb9d6cca78c4719a943b10585
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -533,14 +533,6 @@ def chunk_acTL(self, pos, length): self.im_custom_mimetype = 'image/apng' return s - def chunk_fcTL(self, pos, length): - s = ImageFile._safe_read(self.fp, length) - return s - - def chunk_fdAT(self, pos, length): - s = ImageFile._safe_read(self.fp, length) - return s - # -------------------------------------------------------------------- # PNG reader @@ -682,6 +674,9 @@ def load_end(self): break except EOFError: ImageFile._safe_read(self.fp, length) + except AttributeError: + logger.debug("%r %s %s (unknown)", cid, pos, length) + ImageFile._safe_read(self.fp, length) self._text = self.png.im_text self.png.close() self.png = None
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -596,6 +596,7 @@ def test_apng(self): im = Image.open("Tests/images/iss634.apng") self.assertEqual(im.get_format_mimetype(), 'image/apng') + # This also tests reading unknown PNG chunks (fcTL and fdAT) in load_end expected = Image.open("Tests/images/iss634.webp") self.assert_image_similar(im, expected, 0.23)
Error opening png file ### What did you do? I tried to open image ### What did you expect to happen? Image to be opened without errors ### What actually happened? Pillow raised error. Traceback: ``` File "/usr/local/lib/python3.6/dist-packages/PIL/Image.py", line 915, in convert self.load() File "/usr/local/lib/python3.6/dist-packages/PIL/ImageFile.py", line 252, in load self.load_end() File "/usr/local/lib/python3.6/dist-packages/PIL/PngImagePlugin.py", line 680, in load_end self.png.call(cid, pos, length) File "/usr/local/lib/python3.6/dist-packages/PIL/PngImagePlugin.py", line 140, in call return getattr(self, "chunk_" + cid.decode('ascii'))(pos, length) AttributeError: 'PngStream' object has no attribute 'chunk_eXIf ``` ## What are your OS, Python and Pillow versions? * OS: Ubuntu 18.04.1 LTS x86_64 * Python: 3.6 * Pillow: 5.4.1 ## Demonstration code ```python from PIL import Image img = Image.open('50767927-ad61c580-128f-11e9-879e-502cf52fc129.png') img.load() ``` ![Image causing troubles](https://user-images.githubusercontent.com/22667809/50767927-ad61c580-128f-11e9-879e-502cf52fc129.png) edit: Pillow version I use is 5.4.1, not 3.4.1
With: * macOS High Sierra * Python 3.7.2 Cannot reproduce with: * Pillow 3.4.1 * Pillow 5.3.0 Can reproduce with: * Pillow 5.4.0 * Pillow 5.4.1 (latest) Git bisect points to 22837c37e279a5fb3fb7b482d81e2c4d44c8cdcc from https://github.com/python-pillow/Pillow/pull/3506: ``` 22837c37e279a5fb3fb7b482d81e2c4d44c8cdcc is the first bad commit commit 22837c37e279a5fb3fb7b482d81e2c4d44c8cdcc Date: Mon Dec 24 23:58:19 2018 +1100 Read textual chunks located after IDAT chunks :040000 040000 bbc4e38e995ac826609218792b542d89d25ea138 efdb2cef1a1a438728c23dd94d162d23a8579df7 M Tests :040000 040000 5f47d2133fdfa73a7753f08203eb79d1d820a4e4 e38923295adea6da49623e6775bc95dfe483952c M src ```
2019-01-07T20:53:24Z
5.4
python-pillow/Pillow
3,513
python-pillow__Pillow-3513
[ "2745" ]
5d9a3273d5a6952fd111490665f90e160e1dab03
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -557,26 +557,26 @@ def _setitem(self, tag, value, legacy_api): else: self.tagtype[tag] = 7 if all(isinstance(v, IFDRational) for v in values): - self.tagtype[tag] = 5 + self.tagtype[tag] = TiffTags.RATIONAL elif all(isinstance(v, int) for v in values): if all(v < 2 ** 16 for v in values): - self.tagtype[tag] = 3 + self.tagtype[tag] = TiffTags.SHORT else: - self.tagtype[tag] = 4 + self.tagtype[tag] = TiffTags.LONG elif all(isinstance(v, float) for v in values): - self.tagtype[tag] = 12 + self.tagtype[tag] = TiffTags.DOUBLE else: if py3: if all(isinstance(v, str) for v in values): - self.tagtype[tag] = 2 + self.tagtype[tag] = TiffTags.ASCII else: # Never treat data as binary by default on Python 2. - self.tagtype[tag] = 2 + self.tagtype[tag] = TiffTags.ASCII - if self.tagtype[tag] == 7 and py3: + if self.tagtype[tag] == TiffTags.UNDEFINED and py3: values = [value.encode("ascii", 'replace') if isinstance( value, str) else value] - elif self.tagtype[tag] == 5: + elif self.tagtype[tag] == TiffTags.RATIONAL: values = [float(v) if isinstance(v, int) else v for v in values] @@ -592,7 +592,10 @@ def _setitem(self, tag, value, legacy_api): if (info.length == 1) or \ (info.length is None and len(values) == 1 and not legacy_api): # Don't mess with the legacy api, since it's frozen. - if legacy_api and self.tagtype[tag] in [5, 10]: # rationals + if legacy_api and self.tagtype[tag] in [ + TiffTags.RATIONAL, + TiffTags.SIGNED_RATIONAL + ]: # rationals values = values, try: dest[tag], = values @@ -649,13 +652,13 @@ def _register_basic(idx_fmt_name): b"".join(self._pack(fmt, value) for value in values)) list(map(_register_basic, - [(3, "H", "short"), - (4, "L", "long"), - (6, "b", "signed byte"), - (8, "h", "signed short"), - (9, "l", "signed long"), - (11, "f", "float"), - (12, "d", "double")])) + [(TiffTags.SHORT, "H", "short"), + (TiffTags.LONG, "L", "long"), + (TiffTags.SIGNED_BYTE, "b", "signed byte"), + (TiffTags.SIGNED_SHORT, "h", "signed short"), + (TiffTags.SIGNED_LONG, "l", "signed long"), + (TiffTags.FLOAT, "f", "float"), + (TiffTags.DOUBLE, "d", "double")])) @_register_loader(1, 1) # Basic type, except for the legacy API. def load_byte(self, data, legacy_api=True): @@ -811,7 +814,10 @@ def save(self, fp): print("- value:", values) # count is sum of lengths for string and arbitrary data - count = len(data) if typ in [2, 7] else len(values) + if typ in [TiffTags.ASCII, TiffTags.UNDEFINED]: + count = len(data) + else: + count = len(values) # figure out if data fits into the entry if len(data) <= 4: entries.append((tag, typ, count, data.ljust(4, b"\0"), b"")) @@ -1513,12 +1519,16 @@ def _save(im, fp, filename): getattr(im, 'tag_v2', {}).items(), legacy_ifd.items()): # Libtiff can only process certain core items without adding - # them to the custom dictionary. Support has only been been added - # for int and float values + # them to the custom dictionary. + # Support for custom items has only been been added + # for int, float, unicode, string and byte values if tag not in TiffTags.LIBTIFF_CORE: + if TiffTags.lookup(tag).type == TiffTags.UNDEFINED: + continue if (distutils.version.StrictVersion(_libtiff_version()) < distutils.version.StrictVersion("4.0")) \ - or not (isinstance(value, int) or isinstance(value, float)): + or not (isinstance(value, (int, float, str, bytes)) or + (not py3 and isinstance(value, unicode))): # noqa: F821 continue if tag not in atts and tag not in blocklist: if isinstance(value, str if py3 else unicode): # noqa: F821 @@ -1799,7 +1809,7 @@ def fixOffsets(self, count, isShort=False, isLong=False): # local (not referenced with another offset) self.rewriteLastShortToLong(offset) self.f.seek(-10, os.SEEK_CUR) - self.writeShort(4) # rewrite the type to LONG + self.writeShort(TiffTags.LONG) # rewrite the type to LONG self.f.seek(8, os.SEEK_CUR) elif isShort: self.rewriteLastShort(offset) diff --git a/src/PIL/TiffTags.py b/src/PIL/TiffTags.py --- a/src/PIL/TiffTags.py +++ b/src/PIL/TiffTags.py @@ -64,8 +64,12 @@ def lookup(tag): SHORT = 3 LONG = 4 RATIONAL = 5 +SIGNED_BYTE = 6 UNDEFINED = 7 +SIGNED_SHORT = 8 +SIGNED_LONG = 9 SIGNED_RATIONAL = 10 +FLOAT = 11 DOUBLE = 12 TAGS_V2 = {
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -235,7 +235,10 @@ def test_additional_metadata(self): def test_custom_metadata(self): custom = { 37000: 4, - 37001: 4.2 + 37001: 4.2, + 37002: 'custom tag value', + 37003: u'custom tag value', + 37004: b'custom tag value' } libtiff_version = TiffImagePlugin._libtiff_version() @@ -256,6 +259,8 @@ def test_custom_metadata(self): reloaded = Image.open(out) for tag, value in custom.items(): + if libtiff and isinstance(value, bytes): + value = value.decode() self.assertEqual(reloaded.tag_v2[tag], value) def test_int_dpi(self):
Failed to write customized tag into Tiff file I am using python version 2.7 I am trying to write some custom tag(37000 in this case) into new tiff file. It is able to read tag from image but when I am trying to write them it is not successfully written. When I am use pillow 4.1.0 to do that, tag is not added, and then when I tried old version pillow 2.3, tag is added successfully but cannot save image correctly (only blank) Could you give me some help, I appreciate that! Here is the testing code: ```python from PIL import Image, TiffImagePlugin, TiffTags def test_custom_metadata(): img = Image.open('mytifffile.tif') img.tag[37000]='my special tag' info = TiffImagePlugin.ImageFileDirectory() CustomTagId = 37000 info[CustomTagId] = 'my special tag' print(img.tag) Image.DEBUG=True TiffImagePlugin.WRITE_LIBTIFF = False # Set to True to see it break. img.save('temp2.tif',tiffinfo= img.tag) img2 = Image.open('temp2.tif') print(img2.tag) test_custom_metadata() ``` outputs are: `{256: (1703,), 257: (937,), 258: (8,), 259: (5,), 262: (1,), 296: (1,), 273: (8,), 274: (1,), 339: (1,), 277: (1,), 278: (937,), 279: (1849679,), 37000: ('my special tag',), 284: (1,)} ` `{256: (1703,), 257: (937,), 258: (8,), 259: (5,), 262: (1,), 296: (1,), 273: (8,), 274: (1,), 339: (1,), 277: (1,), 278: (937,), 279: (1849679,), 284: (1,)}` As you can see, `37000: ('my special tag',)` is missing. I doing this because, my original tiff file have some customized tag(51023), and it is 16 bit. So what I want to do is to rescale it to 8 bit which is able to do and keep that tag(51023) and value as it is.
Unfortunately, Tiff IFD tags are a bit of a mess when writing. The native python tiff writer will write arbitrary tags, but it's limited to raw, uncompressed pixel data. The libtiff writer is limited to only the standard builtin tags, and at that, only a subset. We do not currently implement the api methods required to do arbitrary metadata through libtiff.
2018-12-29T05:35:47Z
5.3
python-pillow/Pillow
3,479
python-pillow__Pillow-3479
[ "1718" ]
080bfd3ee1412b401d520fe26c51e2f5515e3a65
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -201,7 +201,13 @@ def _seek(self, frame): # # comment extension # - info["comment"] = block + while block: + if "comment" in info: + info["comment"] += block + else: + info["comment"] = block + block = self.data() + continue elif i8(s) == 255: # # application extension @@ -536,12 +542,14 @@ def _write_local_header(fp, im, offset, flags): o8(0)) if "comment" in im.encoderinfo and \ - 1 <= len(im.encoderinfo["comment"]) <= 255: + 1 <= len(im.encoderinfo["comment"]): fp.write(b"!" + - o8(254) + # extension intro - o8(len(im.encoderinfo["comment"])) + - im.encoderinfo["comment"] + - o8(0)) + o8(254)) # extension intro + for i in range(0, len(im.encoderinfo["comment"]), 255): + subblock = im.encoderinfo["comment"][i:i+255] + fp.write(o8(len(subblock)) + + subblock) + fp.write(o8(0)) if "loop" in im.encoderinfo: number_of_loops = im.encoderinfo["loop"] fp.write(b"!" +
diff --git a/Tests/images/hopper_zero_comment_subblocks.gif b/Tests/images/hopper_zero_comment_subblocks.gif new file mode 100644 Binary files /dev/null and b/Tests/images/hopper_zero_comment_subblocks.gif differ diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -435,6 +435,23 @@ def test_comment(self): self.assertEqual(reread.info['comment'], im.info['comment']) + def test_comment_over_255(self): + out = self.tempfile('temp.gif') + im = Image.new('L', (100, 100), '#000') + comment = b"Test comment text" + while len(comment) < 256: + comment += comment + im.info['comment'] = comment + im.save(out) + reread = Image.open(out) + + self.assertEqual(reread.info['comment'], comment) + + def test_zero_comment_subblocks(self): + im = Image.open('Tests/images/hopper_zero_comment_subblocks.gif') + expected = Image.open(TEST_GIF) + self.assert_image_equal(im, expected) + def test_version(self): out = self.tempfile('temp.gif')
GIF decoder can't handle zero-length extension blocks To reproduce: ``` python >>> import io, PIL.Image >>> PIL.Image.open(io.BytesIO(bytes.fromhex('47 49 46 38 39 61 01 00 01 00 80 00 00 FF FF FF 00 00 00 21 FE 00 2C 00 00 00 00 01 00 01 00 00 02 02 44 01 00 3B'))) ```
I presume that this image is able to be redistributed as a image in the test suite under Pillow's license? Just to post information here, an EOFError is being raised at https://github.com/python-pillow/Pillow/blob/384d32969d3f6701477a616356ed5c180215103a/PIL/GifImagePlugin.py#L266
2018-11-27T19:02:54Z
5.3
python-pillow/Pillow
3,364
python-pillow__Pillow-3364
[ "3339" ]
d4000a8f728e051a4da811a9ea23144e6b5fe6c3
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -221,6 +221,50 @@ def colorize(image, black, white, mid=None, blackpoint=0, return _lut(image, red + green + blue) +def pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)): + """ + Returns a sized and padded version of the image, expanded to fill the + requested aspect ratio and size. + + :param image: The image to size and crop. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: What resampling method to use. Default is + :py:attr:`PIL.Image.NEAREST`. + :param color: The background color of the padded image. + :param centering: Control the position of the original image within the + padded version. + (0.5, 0.5) will keep the image centered + (0, 0) will keep the image aligned to the top left + (1, 1) will keep the image aligned to the bottom + right + :return: An image. + """ + + im_ratio = image.width / image.height + dest_ratio = float(size[0]) / size[1] + + if im_ratio == dest_ratio: + out = image.resize(size, resample=method) + else: + out = Image.new(image.mode, size, color) + if im_ratio > dest_ratio: + new_height = int(image.height / image.width * size[0]) + if new_height != size[1]: + image = image.resize((size[0], new_height), resample=method) + + y = int((size[1] - new_height) * max(0, min(centering[1], 1))) + out.paste(image, (0, y)) + else: + new_width = int(image.width / image.height * size[1]) + if new_width != size[0]: + image = image.resize((new_width, size[1]), resample=method) + + x = int((size[0] - new_width) * max(0, min(centering[0], 1))) + out.paste(image, (x, 0)) + return out + + def crop(image, border=0): """ Remove border from image. The same amount of pixels are removed
diff --git a/Tests/images/imageops_pad_h_0.jpg b/Tests/images/imageops_pad_h_0.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/imageops_pad_h_0.jpg differ diff --git a/Tests/images/imageops_pad_h_1.jpg b/Tests/images/imageops_pad_h_1.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/imageops_pad_h_1.jpg differ diff --git a/Tests/images/imageops_pad_h_2.jpg b/Tests/images/imageops_pad_h_2.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/imageops_pad_h_2.jpg differ diff --git a/Tests/images/imageops_pad_v_0.jpg b/Tests/images/imageops_pad_v_0.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/imageops_pad_v_0.jpg differ diff --git a/Tests/images/imageops_pad_v_1.jpg b/Tests/images/imageops_pad_v_1.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/imageops_pad_v_1.jpg differ diff --git a/Tests/images/imageops_pad_v_2.jpg b/Tests/images/imageops_pad_v_2.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/imageops_pad_v_2.jpg differ diff --git a/Tests/test_imageops.py b/Tests/test_imageops.py --- a/Tests/test_imageops.py +++ b/Tests/test_imageops.py @@ -24,6 +24,9 @@ def test_sanity(self): ImageOps.colorize(hopper("L"), (0, 0, 0), (255, 255, 255)) ImageOps.colorize(hopper("L"), "black", "white") + ImageOps.pad(hopper("L"), (128, 128)) + ImageOps.pad(hopper("RGB"), (128, 128)) + ImageOps.crop(hopper("L"), 1) ImageOps.crop(hopper("RGB"), 1) @@ -70,6 +73,27 @@ def test_1pxfit(self): newimg = ImageOps.fit(hopper("RGB").resize((100, 1)), (35, 35)) self.assertEqual(newimg.size, (35, 35)) + def test_pad(self): + # Same ratio + im = hopper() + new_size = (im.width * 2, im.height * 2) + new_im = ImageOps.pad(im, new_size) + self.assertEqual(new_im.size, new_size) + + for label, color, new_size in [ + ("h", None, (im.width * 4, im.height * 2)), + ("v", "#f00", (im.width * 2, im.height * 4)) + ]: + for i, centering in enumerate([(0,0), (0.5, 0.5), (1, 1)]): + new_im = ImageOps.pad(im, new_size, + color=color, centering=centering) + self.assertEqual(new_im.size, new_size) + + target = Image.open( + "Tests/images/imageops_pad_"+label+"_"+str(i)+".jpg") + self.assert_image_similar(new_im, target, 6) + + def test_pil163(self): # Division by zero in equalize if < 255 pixels in image (@PIL163)
Suggestion: option to pad instead of crop in ImageOps.fit I recently wanted to use Pillow to generate thumbnails of a directory of images. I wanted each thumbnail to be exactly 300x200, but preserve the aspect ratio of the original image by padding one of the dimensions. I thought [`PIL.ImageOps.fit`](https://pillow.readthedocs.io/en/latest/reference/ImageOps.html?highlight=ImageOps#PIL.ImageOps.fit) might do exactly what I wanted, but it crops rather than padding. Would there be interest in an option to pad rather than crop? Or another method? I'd be happy to contribute if so. PIL 1.1.7, Python 3.6.5
Here is another method - ```python from PIL import Image im = Image.open("test.png") w, h = 300, 200 ratio = im.width / im.height if ratio == w / h: out = im.resize((w, h)) else: out = Image.new(im.mode, (w, h)) if ratio > w / h: new_h = int(im.height / im.width * w) im = im.resize((w, new_h)) out.paste(im, (0, int((h - new_h) / 2))) else: new_w = int(im.width / im.height * h) im = im.resize((new_w, h)) out.paste(im, (int((w - new_w) / 2), 0)) ``` Yep, that's a way to do it. My proposal would be to either fold that in to `PIL.ImageOps.fit` or make it another method on `ImageOps`. Oh, apologies - when you said 'Or another method?', I interpreted that differently. I have created PR #3364 to add a method for this.
2018-09-18T11:11:01Z
5.2
python-pillow/Pillow
3,338
python-pillow__Pillow-3338
[ "1765" ]
41954f244705b247667f1ea228e932ca6390bcd6
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -567,6 +567,9 @@ def _setitem(self, tag, value, legacy_api): if self.tagtype[tag] == 7 and py3: values = [value.encode("ascii", 'replace') if isinstance( value, str) else value] + elif self.tagtype[tag] == 5: + values = [float(v) if isinstance(v, int) else v + for v in values] values = tuple(info.cvt_enum(value) for value in values)
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -231,6 +231,16 @@ def test_additional_metadata(self): TiffImagePlugin.WRITE_LIBTIFF = False + def test_int_dpi(self): + # issue #1765 + im = hopper('RGB') + out = self.tempfile('temp.tif') + TiffImagePlugin.WRITE_LIBTIFF = True + im.save(out, dpi=(72, 72)) + TiffImagePlugin.WRITE_LIBTIFF = False + reloaded = Image.open(out) + self.assertEqual(reloaded.info['dpi'], (72.0, 72.0)) + def test_g3_compression(self): i = Image.open('Tests/images/hopper_g4_500.tif') out = self.tempfile("temp.tif")
Save compressed TIFF only accepts float values for dpi There is a trap in setting the resolution for compressed TIFF images. ```python # pillow v3.1.1 import PIL.Image im = PIL.Image.new('CMYK', (100, 100)) dpi = 100.0 # works dpi = 100 # fails im.save('test.tif', format='TIFF', dpi=(dpi, dpi), compression='tiff_lzw', #compression='tiff_deflate', #compression='tiff_adobe_deflate' ) ``` Integers fail silently resulting in the resolution value missing from the saved file. Floats work as expected.
2018-09-07T10:51:11Z
5.2
python-pillow/Pillow
3,233
python-pillow__Pillow-3233
[ "3231" ]
5e0682ed6a957ef0e6bf6f70bb0438cfdfc9b48c
diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -246,7 +246,7 @@ def multiline_text(self, xy, text, fill=None, font=None, anchor=None, elif align == "right": left += (max_width - widths[idx]) else: - assert False, 'align must be "left", "center" or "right"' + raise ValueError('align must be "left", "center" or "right"') self.text((left, top), line, fill, font, anchor, direction=direction, features=features) top += line_spacing diff --git a/src/PIL/ImageTk.py b/src/PIL/ImageTk.py --- a/src/PIL/ImageTk.py +++ b/src/PIL/ImageTk.py @@ -32,13 +32,6 @@ else: import Tkinter as tkinter -# required for pypy, which always has cffi installed -try: - from cffi import FFI - ffi = FFI() -except ImportError: - pass - from . import Image from io import BytesIO @@ -192,7 +185,11 @@ def paste(self, im, box=None): from . import _imagingtk try: if hasattr(tk, 'interp'): - # Pypy is using a ffi cdata element + # Required for PyPy, which always has CFFI installed + from cffi import FFI + ffi = FFI() + + # PyPy is using an FFI CDATA element # (Pdb) self.tk.interp # <cdata 'Tcl_Interp *' 0x3061b50> _imagingtk.tkinit( diff --git a/src/PIL/__init__.py b/src/PIL/__init__.py --- a/src/PIL/__init__.py +++ b/src/PIL/__init__.py @@ -1,4 +1,4 @@ -"""Pillow {} (Fork of the Python Imaging Library) +"""Pillow (Fork of the Python Imaging Library) Pillow is the friendly PIL fork by Alex Clark and Contributors. https://github.com/python-pillow/Pillow/ @@ -24,8 +24,6 @@ del _version -__doc__ = __doc__.format(__version__) # include version in docstring - _plugins = ['BlpImagePlugin', 'BmpImagePlugin',
diff --git a/Tests/test_image_access.py b/Tests/test_image_access.py --- a/Tests/test_image_access.py +++ b/Tests/test_image_access.py @@ -1,15 +1,20 @@ from helper import unittest, PillowTestCase, hopper, on_appveyor -try: - from PIL import PyAccess -except ImportError: - # Skip in setUp() - pass - from PIL import Image import sys import os +# CFFI imports pycparser which doesn't support PYTHONOPTIMIZE=2 +# https://github.com/eliben/pycparser/pull/198#issuecomment-317001670 +if os.environ.get("PYTHONOPTIMIZE") == "2": + cffi = None +else: + try: + from PIL import PyAccess + import cffi + except ImportError: + cffi = None + class AccessTest(PillowTestCase): # initial value @@ -113,38 +118,20 @@ def test_signedness(self): self.check(mode, 2**16-1) +@unittest.skipIf(cffi is None, "No cffi") class TestCffiPutPixel(TestImagePutPixel): _need_cffi_access = True - def setUp(self): - try: - import cffi - assert cffi # silence warning - except ImportError: - self.skipTest("No cffi") - +@unittest.skipIf(cffi is None, "No cffi") class TestCffiGetPixel(TestImageGetPixel): _need_cffi_access = True - def setUp(self): - try: - import cffi - assert cffi # silence warning - except ImportError: - self.skipTest("No cffi") - +@unittest.skipIf(cffi is None, "No cffi") class TestCffi(AccessTest): _need_cffi_access = True - def setUp(self): - try: - import cffi - assert cffi # silence warning - except ImportError: - self.skipTest("No cffi") - def _test_get_access(self, im): """Do we get the same thing as the old pixel access diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -215,7 +215,7 @@ def test_unknown_align(self): # Act/Assert self.assertRaises( - AssertionError, + ValueError, draw.multiline_text, (0, 0), TEST_TEXT, font=ttf, align="unknown") def test_draw_align(self):
Pillow cannot be loaded in python optimize (2) mode ### What did you do? I was loading the PIL module with 'import PIL' when running Python with PYTHONOPTIMZE=2 (or python -OO). ### What did you expect to happen? I Expected the PIL/Pillow Library to be imported. ### What actually happened? I received an exception: AttributeError: 'NoneType' object has no attribute 'format' ### What versions of Pillow and Python are you using? Pillow 5.2.0 / Python 3.6.5 ### Reason: PYTHONOPTIMIZE=2 / python -OO strips the _ _ doc _ _ variable. ## Example: create a file called test.py with only import PIL ```python import PIL ``` Execute it with python in optimize mode ```sh python -OO test.py ``` You will receive the following exception: ``` Traceback (most recent call last): File "test.py", line 1, in <module> import PIL File "/usr/lib/python3.6/site-packages/PIL/__init__.py", line 27, in <module> __doc__ = __doc__.format(__version__) # include version in docstring AttributeError: 'NoneType' object has no attribute 'format' ```
2018-07-04T17:35:30Z
5.2
python-pillow/Pillow
3,086
python-pillow__Pillow-3086
[ "3073" ]
e24fad40ad67fac3d86e1a826fbf91b4d2fe7c90
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -457,7 +457,8 @@ def _save_all(im, fp, filename): def _save(im, fp, filename, save_all=False): - im.encoderinfo.update(im.info) + for k, v in im.info.items(): + im.encoderinfo.setdefault(k, v) # header try: palette = im.encoderinfo["palette"]
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -305,9 +305,12 @@ def test_duration(self): out = self.tempfile('temp.gif') im = Image.new('L', (100, 100), '#000') + + # Check that the argument has priority over the info settings + im.info['duration'] = 100 im.save(out, duration=duration) - reread = Image.open(out) + reread = Image.open(out) self.assertEqual(reread.info['duration'], duration) def test_multiple_duration(self):
Gif duration setting is ignored ### What versions of Pillow and Python are you using? Python 3.6.4 Pillow 5.0 Any animated gif I have tried the following lines of code on show no affect on the gif frame duration: ```python > from PIL import Image > f = Image.open('in.gif') > f.save('out.gif', save_all=True, duration=400) ```
Hi. To help with your immediate problem, try this - ```python from PIL import Image f = Image.open('in.gif') f.info['duration'] = 400 f.save('out.gif', save_all=True) ``` What I'm guessing is happening is that the images you are opening already have a `duration` key, and this key is overwriting the `duration` argument you are passing in on save.
2018-04-10T12:34:37Z
5.1
python-pillow/Pillow
3,023
python-pillow__Pillow-3023
[ "3022" ]
262b6d15ccc5af3e31f6b6a8092ff9808bd991ff
diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py --- a/src/PIL/ImageFile.py +++ b/src/PIL/ImageFile.py @@ -202,44 +202,39 @@ def load(self): for decoder_name, extents, offset, args in self.tile: decoder = Image._getdecoder(self.mode, decoder_name, args, self.decoderconfig) - seek(offset) - decoder.setimage(self.im, extents) - if decoder.pulls_fd: - decoder.setfd(self.fp) - status, err_code = decoder.decode(b"") - else: - b = prefix - while True: - try: - s = read(self.decodermaxblock) - except (IndexError, struct.error): # truncated png/gif - if LOAD_TRUNCATED_IMAGES: - break - else: - raise IOError("image file is truncated") - - if not s: # truncated jpeg - self.tile = [] - - # JpegDecode needs to clean things up here either way - # If we don't destroy the decompressor, - # we have a memory leak. - decoder.cleanup() - - if LOAD_TRUNCATED_IMAGES: + try: + seek(offset) + decoder.setimage(self.im, extents) + if decoder.pulls_fd: + decoder.setfd(self.fp) + status, err_code = decoder.decode(b"") + else: + b = prefix + while True: + try: + s = read(self.decodermaxblock) + except (IndexError, struct.error): # truncated png/gif + if LOAD_TRUNCATED_IMAGES: + break + else: + raise IOError("image file is truncated") + + if not s: # truncated jpeg + if LOAD_TRUNCATED_IMAGES: + break + else: + self.tile = [] + raise IOError("image file is truncated " + "(%d bytes not processed)" % len(b)) + + b = b + s + n, err_code = decoder.decode(b) + if n < 0: break - else: - raise IOError("image file is truncated " - "(%d bytes not processed)" % len(b)) - - b = b + s - n, err_code = decoder.decode(b) - if n < 0: - break - b = b[n:] - - # Need to cleanup here to prevent leaks in PyPy - decoder.cleanup() + b = b[n:] + finally: + # Need to cleanup here to prevent leaks + decoder.cleanup() self.tile = [] self.readonly = readonly diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py --- a/src/PIL/JpegImagePlugin.py +++ b/src/PIL/JpegImagePlugin.py @@ -353,6 +353,21 @@ def _open(self): else: raise SyntaxError("no marker found") + def load_read(self, read_bytes): + """ + internal: read more image data + For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker + so libjpeg can finish decoding + """ + s = self.fp.read(read_bytes) + + if not s and ImageFile.LOAD_TRUNCATED_IMAGES: + # Premature EOF. + # Pretend file is finished adding EOI marker + return b"\xFF\xD9" + + return s + def draft(self, mode, size): if len(self.tile) != 1:
diff --git a/Tests/images/truncated_jpeg.jpg b/Tests/images/truncated_jpeg.jpg new file mode 100644 Binary files /dev/null and b/Tests/images/truncated_jpeg.jpg differ diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -348,6 +348,22 @@ def test_ff00_jpeg_header(self): filename = "Tests/images/jpeg_ff00_header.jpg" Image.open(filename) + def test_truncated_jpeg_should_read_all_the_data(self): + filename = "Tests/images/truncated_jpeg.jpg" + ImageFile.LOAD_TRUNCATED_IMAGES = True + im = Image.open(filename) + im.load() + ImageFile.LOAD_TRUNCATED_IMAGES = False + self.assertIsNotNone(im.getbbox()) + + def test_truncated_jpeg_throws_IOError(self): + filename = "Tests/images/truncated_jpeg.jpg" + im = Image.open(filename) + + with self.assertRaises(IOError): + im.load() + + def _n_qtables_helper(self, n, test_file): im = Image.open(test_file) f = self.tempfile('temp.jpg')
Corrupt jpeg opens as all black image ### What did you do? ```python from PIL import Image from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True im = Image.open('pic263134.jpg') im.save('1.png') ``` ### What did you expect to happen? Image could be saved up to corruption point. ### What actually happened? All black image is saved. Tried saving to different output formats - it's all black anyway. ![1.png](https://user-images.githubusercontent.com/2279051/36819127-dc9e33ea-1c9c-11e8-9a93-0d3c0a674f02.png) ### What versions of Pillow and Python are you using? Python2. Pillow 5.0.0 and 3.0.0 Original image: ![original_image](https://user-images.githubusercontent.com/2279051/36819109-d04f6f32-1c9c-11e8-97cf-fc244d5aa5e3.jpg) `djpeg` can output image correctly (up to corruption point) Looks like it's problem with decoding step, since after opening, all image bands contain 0-only bytes: ```python sum(im.split()[0].point(lambda x: 0 if x else 1).getdata()) # returns 3097440 ```
2018-03-01T06:19:33Z
5
python-pillow/Pillow
2,899
python-pillow__Pillow-2899
[ "2839" ]
6d2a02c6b1e84906ed2060f547d03d71e23f41d4
diff --git a/PIL/TiffImagePlugin.py b/PIL/TiffImagePlugin.py --- a/PIL/TiffImagePlugin.py +++ b/PIL/TiffImagePlugin.py @@ -1029,21 +1029,8 @@ def _decoder(self, rawmode, layer, tile=None): compression = self._compression if compression == "raw": args = (rawmode, 0, 1) - elif compression == "jpeg": - args = rawmode, "" - if JPEGTABLES in self.tag_v2: - # Hack to handle abbreviated JPEG headers - # Definition of JPEGTABLES is that the count - # is the number of bytes in the tables datastream - # so, it should always be 1 in our tag info - self.tile_prefix = self.tag_v2[JPEGTABLES] elif compression == "packbits": args = rawmode - elif compression == "tiff_lzw": - args = rawmode - if PREDICTOR in self.tag_v2: - # Section 14: Differencing Predictor - self.decoderconfig = (self.tag_v2[PREDICTOR],) return args @@ -1244,14 +1231,7 @@ def _setup(self): offsets = self.tag_v2[STRIPOFFSETS] h = self.tag_v2.get(ROWSPERSTRIP, ysize) w = self.size[0] - if READ_LIBTIFF or self._compression in ["tiff_ccitt", "group3", - "group4", "tiff_jpeg", - "tiff_adobe_deflate", - "tiff_thunderscan", - "tiff_deflate", - "tiff_sgilog", - "tiff_sgilog24", - "tiff_raw_16"]: + if READ_LIBTIFF or self._compression != 'raw': # if DEBUG: # print("Activating g4 compression for whole file") @@ -1285,8 +1265,13 @@ def _setup(self): # we're expecting image byte order. So, if the rawmode # contains I;16, we need to convert from native to image # byte order. - if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode: + if rawmode == 'I;16': rawmode = 'I;16N' + if ';16B' in rawmode: + rawmode = rawmode.replace(';16B', ';16N') + if ';16L' in rawmode: + rawmode = rawmode.replace(';16L', ';16N') + # Offset in the tile tuple is 0, we go from 0,0 to # w,h, and we only do this once -- eds diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -43,7 +43,7 @@ "Blend", "Chops", "Convert", "ConvertYCbCr", "Copy", "Crc32", "Crop", "Dib", "Draw", "Effects", "EpsEncode", "File", "Fill", "Filter", "FliDecode", "Geometry", "GetBBox", "GifDecode", "GifEncode", "HexDecode", - "Histo", "JpegDecode", "JpegEncode", "LzwDecode", "Matrix", "ModeFilter", + "Histo", "JpegDecode", "JpegEncode", "Matrix", "ModeFilter", "Negative", "Offset", "Pack", "PackDecode", "Palette", "Paste", "Quant", "QuantOctree", "QuantHash", "QuantHeap", "PcdDecode", "PcxDecode", "PcxEncode", "Point", "RankFilter", "RawDecode", "RawEncode", "Storage",
diff --git a/Tests/helper.py b/Tests/helper.py --- a/Tests/helper.py +++ b/Tests/helper.py @@ -14,11 +14,22 @@ HAS_UPLOADER = False -try: - import test_image_results - HAS_UPLOADER = True -except ImportError: - pass + +if os.environ.get('SHOW_ERRORS', None): + # local img.show for errors. + HAS_UPLOADER=True + class test_image_results: + @classmethod + def upload(self, a, b): + a.show() + b.show() +else: + try: + import test_image_results + HAS_UPLOADER = True + except ImportError: + pass + def convert_to_comparable(a, b): @@ -99,11 +110,17 @@ def assert_image_equal(self, a, b, msg=None): try: url = test_image_results.upload(a, b) logger.error("Url for test images: %s" % url) - except: + except Exception as msg: pass self.fail(msg or "got different content") + def assert_image_equal_tofile(self, a, filename, msg=None, mode=None): + with Image.open(filename) as img: + if mode: + img = img.convert(mode) + self.assert_image_equal(a, img, msg) + def assert_image_similar(self, a, b, epsilon, msg=None): epsilon = float(epsilon) self.assertEqual( @@ -136,6 +153,12 @@ def assert_image_similar(self, a, b, epsilon, msg=None): pass raise e + def assert_image_similar_tofile(self, a, filename, epsilon, msg=None, mode=None): + with Image.open(filename) as img: + if mode: + img = img.convert(mode) + self.assert_image_similar(a, img, epsilon, msg) + def assert_warning(self, warn_class, func, *args, **kwargs): import warnings diff --git a/Tests/images/copyleft.png b/Tests/images/copyleft.png new file mode 100644 Binary files /dev/null and b/Tests/images/copyleft.png differ diff --git a/Tests/images/pil136.png b/Tests/images/pil136.png new file mode 100644 Binary files /dev/null and b/Tests/images/pil136.png differ diff --git a/Tests/images/pil168.png b/Tests/images/pil168.png new file mode 100644 Binary files /dev/null and b/Tests/images/pil168.png differ diff --git a/Tests/images/tiff_16bit_RGBa_target.png b/Tests/images/tiff_16bit_RGBa_target.png new file mode 100644 Binary files /dev/null and b/Tests/images/tiff_16bit_RGBa_target.png differ diff --git a/Tests/images/tiff_adobe_deflate.png b/Tests/images/tiff_adobe_deflate.png new file mode 100644 Binary files /dev/null and b/Tests/images/tiff_adobe_deflate.png differ diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -1,5 +1,6 @@ from __future__ import print_function from helper import unittest, PillowTestCase, hopper, py3 +from PIL import features from ctypes import c_float import io @@ -15,9 +16,7 @@ class LibTiffTestCase(PillowTestCase): def setUp(self): - codecs = dir(Image.core) - - if "libtiff_encoder" not in codecs or "libtiff_decoder" not in codecs: + if not features.check('libtiff'): self.skipTest("tiff support not available") def _assert_noerr(self, im): @@ -126,6 +125,8 @@ def test_adobe_deflate_tiff(self): im.tile[0][:3], ('tiff_adobe_deflate', (0, 0, 278, 374), 0)) im.load() + self.assert_image_equal_tofile(im, 'Tests/images/tiff_adobe_deflate.png') + def test_write_metadata(self): """ Test metadata writing through libtiff """ for legacy_api in [False, True]: @@ -310,12 +311,7 @@ def test_12bit_rawmode(self): # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0, # so we need to unshift so that the integer values are the same. - im2 = Image.open('Tests/images/12in16bit.tif') - - logger.debug("%s", [img.getpixel((0, idx)) - for img in [im, im2] for idx in range(3)]) - - self.assert_image_equal(im, im2) + self.assert_image_equal_tofile(im, 'Tests/images/12in16bit.tif') def test_blur(self): # test case from irc, how to do blur on b/w image @@ -576,6 +572,51 @@ def test_save_tiff_with_jpegtables(self): # Should not raise UnicodeDecodeError or anything else im.save(outfile) + def test_16bit_RGBa_tiff(self): + im = Image.open("Tests/images/tiff_16bit_RGBa.tiff") + + self.assertEqual(im.mode, "RGBA") + self.assertEqual(im.size, (100, 40)) + self.assertEqual(im.tile, [('tiff_lzw', (0, 0, 100, 40), 0, ('RGBa;16N', 'tiff_lzw', False))]) + im.load() + + self.assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGBa_target.png") + + def test_gimp_tiff(self): + # Read TIFF JPEG images from GIMP [@PIL168] + + codecs = dir(Image.core) + if "jpeg_decoder" not in codecs: + self.skipTest("jpeg support not available") + + filename = "Tests/images/pil168.tif" + im = Image.open(filename) + + self.assertEqual(im.mode, "RGB") + self.assertEqual(im.size, (256, 256)) + self.assertEqual( + im.tile, [('jpeg', (0, 0, 256, 256), 0, ('RGB', 'jpeg', False))] + ) + im.load() + + self.assert_image_equal_tofile(im, "Tests/images/pil168.png") + + def test_sampleformat(self): + # https://github.com/python-pillow/Pillow/issues/1466 + im = Image.open("Tests/images/copyleft.tiff") + self.assertEqual(im.mode, 'RGB') + + self.assert_image_equal_tofile(im, "Tests/images/copyleft.png", mode='RGB') + + def test_lzw(self): + im = Image.open("Tests/images/hopper_lzw.tif") + + self.assertEqual(im.mode, 'RGB') + self.assertEqual(im.size, (128, 128)) + self.assertEqual(im.format, "TIFF") + im2 = hopper() + self.assert_image_similar(im, im2, 5) + if __name__ == '__main__': unittest.main() diff --git a/Tests/test_file_mic.py b/Tests/test_file_mic.py --- a/Tests/test_file_mic.py +++ b/Tests/test_file_mic.py @@ -1,6 +1,6 @@ from helper import unittest, PillowTestCase, hopper -from PIL import Image, ImagePalette +from PIL import Image, ImagePalette, features try: from PIL import MicImagePlugin @@ -13,6 +13,7 @@ @unittest.skipUnless(olefile_installed, "olefile package not installed") +@unittest.skipUnless(features.check('libtiff'), "libtiff not installed") class TestFileMic(PillowTestCase): def test_sanity(self): diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -51,13 +51,7 @@ def test_mac_tiff(self): self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))]) im.load() - def test_16bit_RGBa_tiff(self): - im = Image.open("Tests/images/tiff_16bit_RGBa.tiff") - - self.assertEqual(im.mode, "RGBA") - self.assertEqual(im.size, (100, 40)) - self.assertEqual(im.tile, [('tiff_lzw', (0, 0, 100, 40), 50, 'RGBa;16B')]) - im.load() + self.assert_image_similar_tofile(im, "Tests/images/pil136.png", 1) def test_wrong_bits_per_sample(self): im = Image.open("Tests/images/tiff_wrong_bits_per_sample.tiff") @@ -67,32 +61,6 @@ def test_wrong_bits_per_sample(self): self.assertEqual(im.tile, [('raw', (0, 0, 52, 53), 160, ('RGBA', 0, 1))]) im.load() - def test_gimp_tiff(self): - # Read TIFF JPEG images from GIMP [@PIL168] - - codecs = dir(Image.core) - if "jpeg_decoder" not in codecs: - self.skipTest("jpeg support not available") - - filename = "Tests/images/pil168.tif" - im = Image.open(filename) - - self.assertEqual(im.mode, "RGB") - self.assertEqual(im.size, (256, 256)) - self.assertEqual( - im.tile, [ - ('jpeg', (0, 0, 256, 64), 8, ('RGB', '')), - ('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')), - ('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')), - ('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')), - ]) - im.load() - - def test_sampleformat(self): - # https://github.com/python-pillow/Pillow/issues/1466 - im = Image.open("Tests/images/copyleft.tiff") - self.assertEqual(im.mode, 'RGB') - def test_set_legacy_api(self): with self.assertRaises(Exception): ImageFileDirectory_v2.legacy_api = None @@ -225,12 +193,7 @@ def test_12bit_rawmode(self): # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0, # so we need to unshift so that the integer values are the same. - im2 = Image.open('Tests/images/12in16bit.tif') - - logger.debug("%s", [img.getpixel((0, idx)) - for img in [im, im2] for idx in range(3)]) - - self.assert_image_equal(im, im2) + self.assert_image_equal_tofile(im, 'Tests/images/12in16bit.tif') def test_32bit_float(self): # Issue 614, specific 32-bit float format @@ -436,16 +399,6 @@ def test_with_underscores(self): self.assertEqual(im.tag_v2[X_RESOLUTION], 72) self.assertEqual(im.tag_v2[Y_RESOLUTION], 36) - def test_lzw(self): - # Act - im = Image.open("Tests/images/hopper_lzw.tif") - - # Assert - self.assertEqual(im.mode, 'RGB') - self.assertEqual(im.size, (128, 128)) - self.assertEqual(im.format, "TIFF") - im2 = hopper() - self.assert_image_similar(im, im2, 5) def test_roundtrip_tiff_uint16(self): # Test an image of all '0' values
TIFF_LZW decompression is incorrect for 16bpc image Pillow was refusing to open this TIFF in version 4.2.1. In version 4.3.0, it loads it, but then saving it in any format including TIFF produces a silent corruption. Python 2.7.14 in both cases. This is the reproducing script: ``` from PIL import Image # https://s3-external-1.amazonaws.com/prod-elife-published/articles/32330/elife-32330-fig1-v1.tif src_fp = 'elife-32330-fig1-v1.tif' im = Image.open(src_fp) target_fp = open('result.tif', 'w') im.save(target_fp) ``` In 4.2.1: ``` File "reproducing.py", line 5, in <module> im = Image.open(src_fp) File "/opt/loris/venv/local/lib/python2.7/site-packages/PIL/Image.py", line 2519, in open % (filename if filename else fp)) IOError: cannot identify image file 'elife-32330-fig1-v1.tif' ``` In 4.3.0, no output, file gets stored and corrupted. [elife-32330-fig1-v1.tif.gz](https://github.com/python-pillow/Pillow/files/1450479/elife-32330-fig1-v1.tif.gz) [result.tif.gz](https://github.com/python-pillow/Pillow/files/1450480/result.tif.gz) ![converting to PNG](https://user-images.githubusercontent.com/160299/32500515-918e5826-c3cd-11e7-80c2-5995952cf130.png) I tried to track how the `Image` class changed from 4.2.1 to 4.3.0, but there were too many changes to identify the source. I don't expect it to start to work, but to continue throwing an exception if it can't be read safely.
If you use libtiff instead of the internal tiff decoder, it works: ``` from PIL import Image, TiffImagePlugin TiffImagePlugin.READ_LIBTIFF=True im = Image.open('issue_2839.tif') im.show() ``` This image is a 16bit RGBA image, with tiff_lzw compression. Pillow 4.3.0 added support for the 16 bit RGBA type, though the output image is a lower precision 8 bit per channel RGBA image. Prior to that, there was _no_ support for this image. Pillow (and PIL before it) have had internal support for tiff_lzw compression, but apparently it's either buggy or cannot handle this particular image mode. Forcing the TiffImagePlugin to use the libtiff decoder allows Pillow to properly decode this image.
2017-12-20T11:57:54Z
4.3
python-pillow/Pillow
2,852
python-pillow__Pillow-2852
[ "2837" ]
a3b15c4a5f219451d4e6e2929ea9d983f8468ea9
diff --git a/PIL/Image.py b/PIL/Image.py --- a/PIL/Image.py +++ b/PIL/Image.py @@ -2074,7 +2074,8 @@ def thumbnail(self, size, resample=BICUBIC): # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. - def transform(self, size, method, data=None, resample=NEAREST, fill=1): + def transform(self, size, method, data=None, resample=NEAREST, + fill=1, fillcolor=None): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data @@ -2095,9 +2096,11 @@ def transform(self, size, method, data=None, resample=NEAREST, fill=1): environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`. + :param fillcolor: Optional fill color for the area outside the transform + in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ - + if self.mode == 'LA': return self.convert('La').transform( size, method, data, resample, fill).convert('LA') @@ -2116,13 +2119,15 @@ def transform(self, size, method, data=None, resample=NEAREST, fill=1): if data is None: raise ValueError("missing method data") - im = new(self.mode, size, None) + im = new(self.mode, size, fillcolor) if method == MESH: # list of quads for box, quad in data: - im.__transformer(box, self, QUAD, quad, resample, fill) + im.__transformer(box, self, QUAD, quad, resample, + fillcolor is None) else: - im.__transformer((0, 0)+size, self, method, data, resample, fill) + im.__transformer((0, 0)+size, self, method, data, + resample, fillcolor is None) return im
diff --git a/Tests/test_image_transform.py b/Tests/test_image_transform.py --- a/Tests/test_image_transform.py +++ b/Tests/test_image_transform.py @@ -52,6 +52,17 @@ def test_quad(self): self.assert_image_equal(transformed, scaled) + def test_fill(self): + im = hopper('RGB') + (w, h) = im.size + transformed = im.transform(im.size, Image.EXTENT, + (0, 0, + w*2, h*2), + Image.BILINEAR, + fillcolor = 'red') + + self.assertEqual(transformed.getpixel((w-1,h-1)), (255,0,0)) + def test_mesh(self): # this should be a checkerboard of halfsized hoppers in ul, lr im = hopper('RGBA') @@ -256,6 +267,5 @@ class TestImageTransformPerspective(TestImageTransformAffine): # Repeat all tests for AFFINE transformations with PERSPECTIVE transform = Image.PERSPECTIVE - if __name__ == '__main__': unittest.main()
Affine transformation fill parameter seems to do nothing I would like to use PIL to perform an affine warp on an image, but I want to specify a custom fill value for undefined pixels. The `transform` function seems to have a `fill=1` argument, but it is undocumented and looking further in the code it seems to be unused. Is there any way to get a custom fill value in an affine transform?
I am also interested in this!
2017-11-13T10:00:35Z
4.3
python-pillow/Pillow
2,683
python-pillow__Pillow-2683
[ "2044" ]
52e9c831767eaa60cc1686842f4019e0e9964ad8
diff --git a/PIL/Image.py b/PIL/Image.py --- a/PIL/Image.py +++ b/PIL/Image.py @@ -2423,7 +2423,7 @@ def fromqpixmap(im): _fromarray_typemap = { # (shape, typestr) => mode, rawmode # first two members of shape are set to one - # ((1, 1), "|b1"): ("1", "1"), # broken + ((1, 1), "|b1"): ("1", "1;8"), ((1, 1), "|u1"): ("L", "L"), ((1, 1), "|i1"): ("I", "I;8"), ((1, 1), "<u2"): ("I", "I;16"),
diff --git a/Tests/test_numpy.py b/Tests/test_numpy.py --- a/Tests/test_numpy.py +++ b/Tests/test_numpy.py @@ -39,7 +39,7 @@ def test_numpy_to_image(self): def to_image(dtype, bands=1, boolean=0): if bands == 1: if boolean: - data = [0, 1] * 50 + data = [0, 255] * 50 else: data = list(range(100)) a = numpy.array(data, dtype=dtype) @@ -58,9 +58,9 @@ def to_image(dtype, bands=1, boolean=0): return i # Check supported 1-bit integer formats - self.assertRaises(TypeError, lambda: to_image(numpy.bool)) - self.assertRaises(TypeError, lambda: to_image(numpy.bool8)) - + self.assert_image(to_image(numpy.bool, 1, 1), '1', TEST_IMAGE_SIZE) + self.assert_image(to_image(numpy.bool8, 1, 1), '1', TEST_IMAGE_SIZE) + # Check supported 8-bit integer formats self.assert_image(to_image(numpy.uint8), "L", TEST_IMAGE_SIZE) self.assert_image(to_image(numpy.uint8, 3), "RGB", TEST_IMAGE_SIZE) @@ -213,5 +213,13 @@ def test_zero_size(self): self.assertEqual(im.size, (0, 0)) + def test_bool(self): + # https://github.com/python-pillow/Pillow/issues/2044 + a = numpy.zeros((10,2), dtype=numpy.bool) + a[0][0] = True + + im2 = Image.fromarray(a) + self.assertEqual(im2.getdata()[0], 255) + if __name__ == '__main__': unittest.main()
Image.fromarray does not accept array with dtype=bool ### What did you do? ``` >>> im = Image.new("1", (10,10)) >>> a = np.asarray(im) >>> a.dtype dtype('bool') >>> im2 = Image.fromarray(a) Traceback (most recent call last): File "<input>", line 1, in <module> File "/home/moi/Dokumente/Studium/Thesis/Python/local/lib/python2.7/site-packages/PIL/Image.py", line 2167, in fromarray raise TypeError("Cannot handle this data type") TypeError: Cannot handle this data type ``` ### What did you expect to happen? I expect the same image to be convertable back and forth without error. ### What versions of Pillow and Python are you using? ``` python2.7 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] PIL.VERSION '1.1.7' ```
That's a known issue. See #350 Thanks for the hint. @wiredfool Any update on this? #350 is already closed and seems to handle 1-bit image to numpy array conversion, but not the other way around. The exception can still be reproduced following the steps given by the OP. Note that it is even more weird that the `mode='1'` works but produces erroneous result when being read back into numpy ```python In [62]: im = Image.new("1", (10,10)) In [63]: a = np.array(im) In [64]: a[0][0]=True In [65]: b = np.array(Image.fromarray(a, mode='1'), dtype=np.bool) In [66]: b Out[66]: array([[False, False, False, False, False, False, False, True, False, False], [False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False]], dtype=bool) In [67]: b[0][7] Out[67]: True ``` So the minimal replication is: ``` a = np.zeros((2,10), dtype=np.bool) >>> a[0][0] = True >>> a array([[ True, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False, False, False]], dtype=bool) >>> im2 = Image.fromarray(a, '1') >>> list(im2.getdata())[:10] [0, 0, 0, 0, 0, 0, 0, 255, 0, 0] ``` We don't actually advertise that we support the '|b1' typestr in the array interface for a, and there's no way to pass in some form of mode/rawmode combo. So when you pass in the '1' mode, it's expecting a bit packed buffer, which is not what's actually coming through.
2017-08-16T18:51:13Z
4.2
python-pillow/Pillow
2,410
python-pillow__Pillow-2410
[ "2402" ]
130c9c52a4cd821ef099bfe30d46a9dd24a11aee
diff --git a/PIL/GifImagePlugin.py b/PIL/GifImagePlugin.py --- a/PIL/GifImagePlugin.py +++ b/PIL/GifImagePlugin.py @@ -257,7 +257,7 @@ def _seek(self, frame): # only dispose the extent in this frame if self.dispose: - self.dispose = self.dispose.crop(self.dispose_extent) + self.dispose = self._crop(self.dispose, self.dispose_extent) except (AttributeError, KeyError): pass @@ -280,7 +280,7 @@ def load_end(self): if self._prev_im and self.disposal_method == 1: # we do this by pasting the updated area onto the previous # frame which we then use as the current image content - updated = self.im.crop(self.dispose_extent) + updated = self._crop(self.im, self.dispose_extent) self._prev_im.paste(updated, self.dispose_extent, updated.convert('RGBA')) self.im = self._prev_im diff --git a/PIL/Image.py b/PIL/Image.py --- a/PIL/Image.py +++ b/PIL/Image.py @@ -1042,18 +1042,31 @@ def crop(self, box=None): if box is None: return self.copy() - x0, y0, x1, y1 = map(int, map(round, box)) + return self._new(self._crop(self.im, box)) - if x0 == 0 and y0 == 0 and (x1, y1) == self.size: - return self.copy() + def _crop(self, im, box): + """ + Returns a rectangular region from the core image object im. + + This is equivalent to calling im.crop((x0, y0, x1, y1)), but + includes additional sanity checks. + + :param im: a core image object + :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. + :returns: A core image object. + """ + + x0, y0, x1, y1 = map(int, map(round, box)) if x1 < x0: x1 = x0 if y1 < y0: y1 = y0 - return self._new(self.im.crop((x0, y0, x1, y1))) + _decompression_bomb_check((x1, y1)) + return im.crop((x0, y0, x1, y1)) + def draft(self, mode, size): """ Configures the image file loader so it returns a version of the
diff --git a/Tests/test_decompression_bomb.py b/Tests/test_decompression_bomb.py --- a/Tests/test_decompression_bomb.py +++ b/Tests/test_decompression_bomb.py @@ -1,4 +1,4 @@ -from helper import unittest, PillowTestCase +from helper import unittest, PillowTestCase, hopper from PIL import Image @@ -35,9 +35,24 @@ def test_warning(self): self.assertEqual(Image.MAX_IMAGE_PIXELS, 10) # Act / Assert - self.assert_warning( - Image.DecompressionBombWarning, - lambda: Image.open(TEST_FILE)) + self.assert_warning(Image.DecompressionBombWarning, + lambda: Image.open(TEST_FILE)) + +class TestDecompressionCrop(PillowTestCase): + + def setUp(self): + self.src = hopper() + Image.MAX_IMAGE_PIXELS = self.src.height * self.src.width + + def tearDown(self): + Image.MAX_IMAGE_PIXELS = ORIGINAL_LIMIT + + def testEnlargeCrop(self): + # Crops can extend the extents, therefore we should have the + # same decompression bomb warnings on them. + box = (0, 0, self.src.width * 2, self.src.height * 2) + self.assert_warning(Image.DecompressionBombWarning, + lambda: self.src.crop(box)) if __name__ == '__main__': unittest.main()
out of memory when processing this GIF source: http://lavender.b0.upaiyun.com/ex.gif ![example.jpg](http://lavender.b0.upaiyun.com/ex.gif) ```python import PIL import PIL.Image im = PIL.Image.open('example.gif') print(im.size) print(im.n_frames) # will crash ``` ```shell [root /tmp] python3 run.py (320, 240) Killed ``` The problem appear on this line https://github.com/python-pillow/Pillow/blob/master/PIL/GifImagePlugin.py#L261, self.dispose_extent is very huge. env: python3.5 on linux, free mem is 2G. thanks.
any idea? Well, as you've noted, the dispose_extent of frame 90 is rather large: ``` (Pdb) self.dispose_extent (37042, 49425, 90174, 109354) (Pdb) frame 90 ``` This is fed to crop, which ultimately returns a new image. Or, tries to, as that's a rather large image. Any potential fix for #2383 could interact badly with this, as the dispose_extent winds up being the tile extents as well. Crop should really have the DecompressionBomb warning applied, as it can increase the size of the image. But in this case, we're calling into the core image object crop, not Image.crop, so we'd need to either hoist it to a python level function or call the decompression_bomb_check from the C layer.
2017-02-17T15:26:15Z
4.1
python-pillow/Pillow
2,641
python-pillow__Pillow-2641
[ "2639" ]
0cd84cf9b38c37fa27454cf262514308cc84ab2c
diff --git a/PIL/ImageFont.py b/PIL/ImageFont.py --- a/PIL/ImageFont.py +++ b/PIL/ImageFont.py @@ -36,6 +36,7 @@ class _imagingft_not_installed(object): def __getattr__(self, id): raise ImportError("The _imagingft C module is not installed") + try: from . import _imagingft as core except ImportError: @@ -113,7 +114,6 @@ def getmask(self, text, mode="", *args, **kwargs): return self.font.getmask(text, mode) - ## # Wrapper for FreeType fonts. Application code should use the # <b>truetype</b> factory function to create font objects. @@ -162,7 +162,7 @@ def getoffset(self, text): def getmask(self, text, mode="", direction=None, features=None): return self.getmask2(text, mode, direction=direction, features=features)[0] - def getmask2(self, text, mode="", fill=Image.core.fill, direction=None, features=None): + def getmask2(self, text, mode="", fill=Image.core.fill, direction=None, features=None, *args, **kwargs): size, offset = self.font.getsize(text, direction, features) im = fill("L", size, 0) self.font.render(text, im.id, mode == "1", direction, features) @@ -250,7 +250,7 @@ def truetype(font=None, size=10, index=0, encoding="", and "armn" (Apple Roman). See the FreeType documentation for more information. :param layout_engine: Which layout engine to use, if available: - `ImageFont.LAYOUT_BASIC` or `ImageFont.LAYOUT_RAQM`. + `ImageFont.LAYOUT_BASIC` or `ImageFont.LAYOUT_RAQM`. :return: A font object. :exception IOError: If the file could not be read. """
diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -40,13 +40,15 @@ def __exit__(self, type, value, traceback): else: delattr(self._parent_obj, self._attr_name) + @unittest.skipUnless(HAS_FREETYPE, "ImageFont not Available") class TestImageFont(PillowTestCase): LAYOUT_ENGINE = ImageFont.LAYOUT_BASIC # Freetype has different metrics depending on the version. # (and, other things, but first things first) - METRICS = { ('2', '3'): {'multiline': 30, + METRICS = { + ('2', '3'): {'multiline': 30, 'textsize': 12, 'getters': (13, 16)}, ('2', '7'): {'multiline': 6.2, @@ -213,6 +215,14 @@ def test_unknown_align(self): font=ttf, align="unknown")) + def test_draw_align(self): + im = Image.new('RGB', (300, 100), 'white') + draw = ImageDraw.Draw(im) + ttf = self.get_font() + line = "some text" + draw.text((100, 40), line, (0, 0, 0), font=ttf, align='left') + del draw + def test_multiline_size(self): ttf = self.get_font() im = Image.new(mode='RGB', size=(300, 100)) @@ -395,7 +405,7 @@ def test_default_font(self): def test_getsize_empty(self): font = self.get_font() - # should not crash. + # should not crash. self.assertEqual((0, 0), font.getsize('')) def _test_fake_loading_font(self, path_to_fake, fontname): @@ -494,5 +504,6 @@ def test_imagefont_getters(self): class TestImageFont_RaqmLayout(TestImageFont): LAYOUT_ENGINE = ImageFont.LAYOUT_RAQM + if __name__ == '__main__': unittest.main()
getmask2() got an unexpected keyword argument 'align' ### What did you do? Run a py script that uses PIL ### What did you expect to happen? The script uses PIL to show an image with text ### What actually happened? Error happened ### What versions of Pillow and Python are you using? PIL 4.2.1 and Python 3.5.2 Here is the script I am using https://github.com/Aioxas/ax-cogs/blob/master/horoscope/horoscope.py and the traceback is ```python Exception in command 'tsujiura' Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py", line 50, in wrapped ret = yield from coro(*args, **kwargs) File "/home/yukirin/Kanon/cogs/horoscope.py", line 152, in _cookie self.fortune_process(fortune[0]) File "/home/yukirin/Kanon/cogs/horoscope.py", line 213, in fortune_process draw.text((134, 165), line1, (0, 0, 0), font=font, align="center") File "lib/PIL/ImageDraw.py", line 217, in text mask, offset = font.getmask2(text, self.fontmode, *args, **kwargs) TypeError: getmask2() got an unexpected keyword argument 'align' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/bot.py", line 846, in process_commands yield from command.invoke(ctx) File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py", line 374, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: getmask2() got an unexpected keyword argument 'align' ``` I fixed it by reverting to PIL 4.0.0, so I assume PIL 4.2.1 breaking it? (I was asked by the dev of that script I use to post an issue here)
What kind of font are you using? From https://github.com/Aioxas/ax-cogs/blob/master/horoscope/horoscope.py#L204-L216: ```python def fortune_process(self, fortune): img = Image.open("data/horoscope/cookie.png") draw = ImageDraw.Draw(img) font = ImageFont.truetype("data/horoscope/FortuneCookieNF.ttf", 15) line = fortune.split() sep = " " line1 = sep.join(line[:5]) line2 = sep.join(line[5:10]) line3 = sep.join(line[10:]) draw.text((134, 165), line1, (0, 0, 0), font=font, align="center") draw.text((134, 180), line2, (0, 0, 0), font=font, align="center") draw.text((134, 195), line3, (0, 0, 0), font=font, align="center") img.save("data/horoscope/cookie-edit.png") ``` Font is here: https://github.com/Aioxas/ax-cogs/blob/master/horoscope/data/horoscope/FortuneCookieNF.ttf Reproducible with Pillow 4.2.1 and 4.2.0/Python 2.7.13/macOS Sierra: ```python from PIL import Image, ImageDraw, ImageFont img = Image.new("RGB", (400, 400), "white") draw = ImageDraw.Draw(img) font = ImageFont.truetype("FortuneCookieNF.ttf", 15) line1 = "some text" draw.text((134, 165), line1, (0, 0, 0), font=font, align="center") img.show() ``` And also when changing the font: ```python from PIL import Image, ImageDraw, ImageFont img = Image.new("RGB", (400, 400), "white") draw = ImageDraw.Draw(img) font = ImageFont.truetype("/Library/Fonts/Arial.ttf", 15) line1 = "some text" draw.text((134, 165), line1, (0, 0, 0), font=font, align="center") img.show() ``` ``` Traceback (most recent call last): File "2639.py", line 6, in <module> draw.text((134, 165), line1, (0, 0, 0), font=font, align="center") File "/usr/local/lib/python2.7/site-packages/PIL/ImageDraw.py", line 217, in text mask, offset = font.getmask2(text, self.fontmode, *args, **kwargs) TypeError: getmask2() got an unexpected keyword argument 'align' ``` Works with Pillow 4.1.0. Can be fixed by adding `*args, **kwargs` into: ```python def getmask2(self, text, mode="", fill=Image.core.fill, direction=None, features=None): ```
2017-07-23T21:03:41Z
4.2
python-pillow/Pillow
2,399
python-pillow__Pillow-2399
[ "2398" ]
0f9233623e20599166581e7d63762e8052e29187
diff --git a/PIL/Image.py b/PIL/Image.py --- a/PIL/Image.py +++ b/PIL/Image.py @@ -1715,7 +1715,10 @@ def save(self, fp, format=None, **params): if not format: if ext not in EXTENSION: init() - format = EXTENSION[ext] + try: + format = EXTENSION[ext] + except KeyError: + raise ValueError('unknown file extension: {}'.format(ext)) if format.upper() not in SAVE: init()
diff --git a/Tests/test_image.py b/Tests/test_image.py --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -87,6 +87,11 @@ def test_tempfile(self): reloaded = Image.open(fp) self.assert_image_similar(im, reloaded, 20) + def test_unknown_extension(self): + im = hopper() + temp_file = self.tempfile("temp.unknown") + self.assertRaises(ValueError, lambda: im.save(temp_file)) + def test_internals(self): im = Image.new("L", (100, 100))
cryptic error message when saving to a file without a valid extension ### What did you do? I tried to save a file with an invalid extension, e. g. ".5" ### What did you expect to happen? I would expect getting an error message telling me that pillow doesn't know this extension. ### What actually happened? I got a somewhat cryptic error message: File "/usr/local/lib/python3.5/dist-packages/PIL/Image.py", line 1683, in save format = EXTENSION[ext] KeyError: '.5'` ### What versions of Pillow and Python are you using? Python 3.5.2 with pillow 3.4.2 ``` from PIL import Image im = Image.open('test.jpg') im.save('2.5') # error ``` I think this could be easily fixed by adding a `try`/`except` block around line 1718 in Image.py (line number corresponds to the version on github) that re-raises the exception with a clear error message.
2017-02-13T17:07:44Z
4
python-pillow/Pillow
2,330
python-pillow__Pillow-2330
[ "2032" ]
2152b26515fddab64c6f1e73c7eb0028d8ab1212
diff --git a/PIL/DcxImagePlugin.py b/PIL/DcxImagePlugin.py --- a/PIL/DcxImagePlugin.py +++ b/PIL/DcxImagePlugin.py @@ -41,7 +41,8 @@ class DcxImageFile(PcxImageFile): format = "DCX" format_description = "Intel DCX" - + _close_exclusive_fp_after_loading = False + def _open(self): # Header diff --git a/PIL/FliImagePlugin.py b/PIL/FliImagePlugin.py --- a/PIL/FliImagePlugin.py +++ b/PIL/FliImagePlugin.py @@ -37,7 +37,8 @@ class FliImageFile(ImageFile.ImageFile): format = "FLI" format_description = "Autodesk FLI/FLC Animation" - + _close_exclusive_fp_after_loading = False + def _open(self): # HEAD diff --git a/PIL/GifImagePlugin.py b/PIL/GifImagePlugin.py --- a/PIL/GifImagePlugin.py +++ b/PIL/GifImagePlugin.py @@ -47,6 +47,8 @@ class GifImageFile(ImageFile.ImageFile): format = "GIF" format_description = "Compuserve GIF" + _close_exclusive_fp_after_loading = False + global_palette = None def data(self): diff --git a/PIL/ImImagePlugin.py b/PIL/ImImagePlugin.py --- a/PIL/ImImagePlugin.py +++ b/PIL/ImImagePlugin.py @@ -109,6 +109,7 @@ class ImImageFile(ImageFile.ImageFile): format = "IM" format_description = "IFUNC Image Memory" + _close_exclusive_fp_after_loading = False def _open(self): diff --git a/PIL/Image.py b/PIL/Image.py --- a/PIL/Image.py +++ b/PIL/Image.py @@ -506,6 +506,7 @@ class Image(object): """ format = None format_description = None + _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? @@ -560,14 +561,25 @@ def close(self): """ try: self.fp.close() + self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) + if getattr(self, 'map', None): + self.map = None + # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = deferred_error(ValueError("Operation on closed image")) + if sys.version_info >= (3,4,0): + def __del__(self): + if (hasattr(self, 'fp') and hasattr(self, '_exclusive_fp') + and self.fp and self._exclusive_fp): + self.fp.close() + self.fp = None + def _copy(self): self.load() self.im = self.im.copy() @@ -2391,6 +2403,7 @@ def open(fp, mode="r"): if mode != "r": raise ValueError("bad mode %r" % mode) + exclusive_fp = False filename = "" if isPath(fp): filename = fp @@ -2404,11 +2417,13 @@ def open(fp, mode="r"): if filename: fp = builtins.open(filename, "rb") + exclusive_fp = True try: fp.seek(0) except (AttributeError, io.UnsupportedOperation): fp = io.BytesIO(fp.read()) + exclusive_fp = True prefix = fp.read(16) @@ -2437,8 +2452,11 @@ def _open_core(fp, filename, prefix): im = _open_core(fp, filename, prefix) if im: + im._exclusive_fp = exclusive_fp return im + if exclusive_fp: + fp.close() raise IOError("cannot identify image file %r" % (filename if filename else fp)) diff --git a/PIL/ImageFile.py b/PIL/ImageFile.py --- a/PIL/ImageFile.py +++ b/PIL/ImageFile.py @@ -88,10 +88,13 @@ def __init__(self, fp=None, filename=None): # filename self.fp = open(fp, "rb") self.filename = fp + self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename + # can be overridden + self._exclusive_fp = None try: self._open() @@ -100,6 +103,9 @@ def __init__(self, fp=None, filename=None): KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error) as v: + # close the file only if we have opened it this constructor + if self._exclusive_fp: + self.fp.close() raise SyntaxError(v) if not self.mode or self.size[0] <= 0: @@ -115,6 +121,8 @@ def verify(self): # raise exception if something's wrong. must be called # directly after open, and closes file when finished. + if self._exclusive_fp: + self.fp.close() self.fp = None def load(self): @@ -234,14 +242,16 @@ def load(self): self.tile = [] self.readonly = readonly - self.fp = None # might be shared + self.load_end() + + if self._exclusive_fp and self._close_exclusive_fp_after_loading: + self.fp.close() + self.fp = None if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: # still raised if decoder fails to return anything raise_ioerror(err_code) - self.load_end() - return Image.Image.load(self) def load_prepare(self): diff --git a/PIL/MicImagePlugin.py b/PIL/MicImagePlugin.py --- a/PIL/MicImagePlugin.py +++ b/PIL/MicImagePlugin.py @@ -39,6 +39,7 @@ class MicImageFile(TiffImagePlugin.TiffImageFile): format = "MIC" format_description = "Microsoft Image Composer" + _close_exclusive_fp_after_loading = False def _open(self): diff --git a/PIL/MpoImagePlugin.py b/PIL/MpoImagePlugin.py --- a/PIL/MpoImagePlugin.py +++ b/PIL/MpoImagePlugin.py @@ -39,7 +39,8 @@ class MpoImageFile(JpegImagePlugin.JpegImageFile): format = "MPO" format_description = "MPO (CIPA DC-007)" - + _close_exclusive_fp_after_loading = False + def _open(self): self.fp.seek(0) # prep the fp in order to pass the JPEG test JpegImagePlugin.JpegImageFile._open(self) diff --git a/PIL/SpiderImagePlugin.py b/PIL/SpiderImagePlugin.py --- a/PIL/SpiderImagePlugin.py +++ b/PIL/SpiderImagePlugin.py @@ -97,6 +97,7 @@ class SpiderImageFile(ImageFile.ImageFile): format = "SPIDER" format_description = "Spider 2D image" + _close_exclusive_fp_after_loading = False def _open(self): # check header diff --git a/PIL/TiffImagePlugin.py b/PIL/TiffImagePlugin.py --- a/PIL/TiffImagePlugin.py +++ b/PIL/TiffImagePlugin.py @@ -884,6 +884,7 @@ class TiffImageFile(ImageFile.ImageFile): format = "TIFF" format_description = "Adobe TIFF" + _close_exclusive_fp_after_loading = False def _open(self): "Open the first image in a TIFF file" @@ -969,6 +970,7 @@ def _seek(self, frame): self.__frame += 1 self.fp.seek(self._frame_pos[frame]) self.tag_v2.load(self.fp) + self.__next = self.tag_v2.next # fill the legacy tag/ifd entries self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2) self.__frame = frame @@ -1008,6 +1010,12 @@ def load(self): return self._load_libtiff() return super(TiffImageFile, self).load() + def load_end(self): + # allow closing if we're on the first frame, there's no next + # This is the ImageFile.load path only, libtiff specific below. + if self.__frame == 0 and not self.__next: + self._close_exclusive_fp_after_loading = True + def _load_libtiff(self): """ Overload method triggered when we detect a compressed tiff Calls out to libtiff """ @@ -1085,16 +1093,14 @@ def _load_libtiff(self): self.tile = [] self.readonly = 0 # libtiff closed the fp in a, we need to close self.fp, if possible - if hasattr(self.fp, 'close'): - if not self.__next: + if self._exclusive_fp: + if self.__frame == 0 and not self.__next: self.fp.close() - self.fp = None # might be shared + self.fp = None # might be shared if err < 0: raise IOError(err) - self.load_end() - return Image.Image.load(self) def _setup(self): diff --git a/PIL/XpmImagePlugin.py b/PIL/XpmImagePlugin.py --- a/PIL/XpmImagePlugin.py +++ b/PIL/XpmImagePlugin.py @@ -116,8 +116,6 @@ def load_read(self, bytes): for i in range(ysize): s[i] = self.fp.readline()[1:xsize+1].ljust(xsize) - self.fp = None - return b"".join(s) #
diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -3,6 +3,7 @@ from io import BytesIO import os +import sys from PIL import Image from PIL import ImageFile @@ -501,5 +502,27 @@ def test_save_tiff_with_dpi(self): self.assertEqual(im.info['dpi'], reloaded.info['dpi']) +@unittest.skipUnless(sys.platform.startswith('win32'), "Windows only") +class TestFileCloseW32(PillowTestCase): + def setUp(self): + if "jpeg_encoder" not in codecs or "jpeg_decoder" not in codecs: + self.skipTest("jpeg support not available") + + def test_fd_leak(self): + tmpfile = self.tempfile("temp.jpg") + import os + + with Image.open("Tests/images/hopper.jpg") as im: + im.save(tmpfile) + + im = Image.open(tmpfile) + fp = im.fp + self.assertFalse(fp.closed) + self.assertRaises(Exception, lambda: os.remove(tmpfile)) + im.load() + self.assertTrue(fp.closed) + # this should not fail, as load should have closed the file. + os.remove(tmpfile) + if __name__ == '__main__': unittest.main() diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -401,6 +401,19 @@ def test_multipage(self): TiffImagePlugin.READ_LIBTIFF = False + def test_multipage_nframes(self): + # issue #862 + TiffImagePlugin.READ_LIBTIFF = True + im = Image.open('Tests/images/multipage.tiff') + frames = im.n_frames + self.assertEqual(frames, 3) + for idx in range(frames): + im.seek(0) + # Should not raise ValueError: I/O operation on closed file + im.load() + + TiffImagePlugin.READ_LIBTIFF = False + def test__next(self): TiffImagePlugin.READ_LIBTIFF = True im = Image.open('Tests/images/hopper.tif') diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -1,6 +1,7 @@ import logging from io import BytesIO import struct +import sys from helper import unittest, PillowTestCase, hopper, py3 @@ -468,6 +469,44 @@ def test_saving_icc_profile(self): self.assertEqual(b'Dummy value', reloaded.info['icc_profile']) + def test_close_on_load(self): + # same as test_fd_leak, but runs on unixlike os + tmpfile = self.tempfile("temp.tif") + + with Image.open("Tests/images/uint16_1_4660.tif") as im: + im.save(tmpfile) + + im = Image.open(tmpfile) + fp = im.fp + self.assertFalse(fp.closed) + im.load() + self.assertTrue(fp.closed) + + + +@unittest.skipUnless(sys.platform.startswith('win32'), "Windows only") +class TestFileTiffW32(PillowTestCase): + def test_fd_leak(self): + tmpfile = self.tempfile("temp.tif") + import os + + # this is an mmaped file. + with Image.open("Tests/images/uint16_1_4660.tif") as im: + im.save(tmpfile) + + im = Image.open(tmpfile) + fp = im.fp + self.assertFalse(fp.closed) + self.assertRaises(Exception, lambda: os.remove(tmpfile)) + im.load() + self.assertTrue(fp.closed) + + # this closes the mmap + im.close() + + # this should not fail, as load should have closed the file pointer, + # and close should have closed the mmap + os.remove(tmpfile) if __name__ == '__main__': unittest.main()
Close files after loading Draft for #2019 This PR closes files at least for files which we are opening from filename at least for not sequence formats. This breaks consistency across different codecs, though. Is there any reliable place where we can close files for sequence formats?
2017-01-01T20:32:14Z
4
python-pillow/Pillow
2,328
python-pillow__Pillow-2328
[ "2155" ]
f3751a1f3afb956066bfa69accd28e4f58bfbaac
diff --git a/PIL/Image.py b/PIL/Image.py --- a/PIL/Image.py +++ b/PIL/Image.py @@ -1555,7 +1555,7 @@ def resize(self, size, resample=NEAREST): return self._new(self.im.resize(size, resample)) - def rotate(self, angle, resample=NEAREST, expand=0): + def rotate(self, angle, resample=NEAREST, expand=0, center=None, translate=None): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter @@ -1572,48 +1572,81 @@ def rotate(self, angle, resample=NEAREST, expand=0): :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the - input image. + input image. Note that the expand flag assumes rotation around + the center and no translation. + :param center: Optional center of rotation (a 2-tuple). Origin is + the upper left corner. Default is the center of the image. + :param translate: An optional post-rotate translation (a 2-tuple). :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 - # Fast paths regardless of filter - if angle == 0: - return self.copy() - if angle == 180: - return self.transpose(ROTATE_180) - if angle == 90 and expand: - return self.transpose(ROTATE_90) - if angle == 270 and expand: - return self.transpose(ROTATE_270) + # Fast paths regardless of filter, as long as we're not + # translating or changing the center. + if not (center or translate): + if angle == 0: + return self.copy() + if angle == 180: + return self.transpose(ROTATE_180) + if angle == 90 and expand: + return self.transpose(ROTATE_90) + if angle == 270 and expand: + return self.transpose(ROTATE_270) + + # Calculate the affine matrix. Note that this is the reverse + # transformation (from destination image to source) because we + # want to interpolate the (discrete) destination pixel from + # the local area around the (floating) source pixel. + + # The matrix we actually want (note that it operates from the right): + # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) + # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) + # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) + + # The reverse matrix is thus: + # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) + # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) + # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) + + # In any case, the final translation may be updated at the end to + # compensate for the expand flag. + + w, h = self.size + + if translate is None: + translate = [0, 0] + if center is None: + center = [w / 2.0, h / 2.0] angle = - math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0 - ] - - def transform(x, y, matrix=matrix): + ] + def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a*x + b*y + c, d*x + e*y + f + matrix[2], matrix[5] = transform(-center[0] - translate[0], -center[1] - translate[1], matrix) + matrix[2] += center[0] + matrix[5] += center[1] - w, h = self.size if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): - x, y = transform(x, y) + x, y = transform(x, y, matrix) xx.append(x) yy.append(y) - w = int(math.ceil(max(xx)) - math.floor(min(xx))) - h = int(math.ceil(max(yy)) - math.floor(min(yy))) - - # adjust center - x, y = transform(w / 2.0, h / 2.0) - matrix[2] = self.size[0] / 2.0 - x - matrix[5] = self.size[1] / 2.0 - y + nw = int(math.ceil(max(xx)) - math.floor(min(xx))) + nh = int(math.ceil(max(yy)) - math.floor(min(yy))) + + # We multiply a translation matrix from the right. Because of its + # special form, this is the same as taking the image of the translation vector + # as new translation vector. + matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) + w, h = nw, nh return self.transform((w, h), AFFINE, matrix, resample)
diff --git a/Tests/images/hopper_45.png b/Tests/images/hopper_45.png new file mode 100644 Binary files /dev/null and b/Tests/images/hopper_45.png differ diff --git a/Tests/test_image_rotate.py b/Tests/test_image_rotate.py --- a/Tests/test_image_rotate.py +++ b/Tests/test_image_rotate.py @@ -4,32 +4,100 @@ class TestImageRotate(PillowTestCase): - def test_rotate(self): - def rotate(im, mode, angle): - out = im.rotate(angle) - self.assertEqual(out.mode, mode) - self.assertEqual(out.size, im.size) # default rotate clips output - out = im.rotate(angle, expand=1) - self.assertEqual(out.mode, mode) - if angle % 180 == 0: - self.assertEqual(out.size, im.size) - elif im.size == (0, 0): - self.assertEqual(out.size, im.size) - else: - self.assertNotEqual(out.size, im.size) - - + def rotate(self, im, mode, angle, center=None, translate=None): + out = im.rotate(angle, center=center, translate=translate) + self.assertEqual(out.mode, mode) + self.assertEqual(out.size, im.size) # default rotate clips output + out = im.rotate(angle, center=center, translate=translate, expand=1) + self.assertEqual(out.mode, mode) + if angle % 180 == 0: + self.assertEqual(out.size, im.size) + elif im.size == (0, 0): + self.assertEqual(out.size, im.size) + else: + self.assertNotEqual(out.size, im.size) + + def test_mode(self): for mode in ("1", "P", "L", "RGB", "I", "F"): im = hopper(mode) - rotate(im, mode, 45) + self.rotate(im, mode, 45) + def test_angle(self): for angle in (0, 90, 180, 270): im = Image.open('Tests/images/test-card.png') - rotate(im, im.mode, angle) + self.rotate(im, im.mode, angle) + def test_zero(self): for angle in (0, 45, 90, 180, 270): im = Image.new('RGB',(0,0)) - rotate(im, im.mode, angle) + self.rotate(im, im.mode, angle) + + def test_resample(self): + # Target image creation, inspected by eye. + # >>> im = Image.open('Tests/images/hopper.ppm') + # >>> im = im.rotate(45, resample=Image.BICUBIC, expand=True) + # >>> im.save('Tests/images/hopper_45.png') + + target = Image.open('Tests/images/hopper_45.png') + for (resample, epsilon) in ((Image.NEAREST, 10), + (Image.BILINEAR, 5), + (Image.BICUBIC, 0)): + im = hopper() + im = im.rotate(45, resample=resample, expand=True) + self.assert_image_similar(im, target, epsilon) + + def test_center_0(self): + im = hopper() + target = Image.open('Tests/images/hopper_45.png') + target_origin = target.size[1]/2 + target = target.crop((0, target_origin, 128, target_origin + 128)) + + im = im.rotate(45, center=(0,0), resample=Image.BICUBIC) + + self.assert_image_similar(im, target, 15) + + def test_center_14(self): + im = hopper() + target = Image.open('Tests/images/hopper_45.png') + target_origin = target.size[1] / 2 - 14 + target = target.crop((6, target_origin, 128 + 6, target_origin + 128)) + + im = im.rotate(45, center=(14,14), resample=Image.BICUBIC) + + self.assert_image_similar(im, target, 10) + + def test_translate(self): + im = hopper() + target = Image.open('Tests/images/hopper_45.png') + target_origin = (target.size[1] / 2 - 64) - 5 + target = target.crop((target_origin, target_origin, + target_origin + 128, target_origin + 128)) + + im = im.rotate(45, translate=(5,5), resample=Image.BICUBIC) + + self.assert_image_similar(im, target, 1) + + def test_fastpath_center(self): + # if the center is -1,-1 and we rotate by 90<=x<=270 the + # resulting image should be black + for angle in (90, 180, 270): + im = hopper().rotate(angle, center=(-1,-1)) + self.assert_image_equal(im, Image.new('RGB', im.size, 'black')) + + def test_fastpath_translate(self): + # if we post-translate by -128 + # resulting image should be black + for angle in (0, 90, 180, 270): + im = hopper().rotate(angle, translate=(-128,-128)) + self.assert_image_equal(im, Image.new('RGB', im.size, 'black')) + + def test_center(self): + im = hopper() + self.rotate(im, im.mode, 45, center=(0, 0)) + self.rotate(im, im.mode, 45, translate=(im.size[0]/2, 0)) + self.rotate(im, im.mode, 45, center=(0, 0), translate=(im.size[0]/2, 0)) + + if __name__ == '__main__':
Add center and translate option to Image.rotate. Hi, freeimage has a RotateEx function that allows to set a rotation center and a subsequent translation. Due to the affine matrix used for the interpolation, this is super-easy to implement in Pillow, too, and really makes a lot of sense to provide in the API, as calculating the transformation matrix is not something that every user will be able to do easily. Changes proposed in this pull request: - Add center=(x,y) argument to Image.rotate - Add translate=(x,y) argument to Image.rotate - Documentation and tests for these.
2017-01-01T11:16:48Z
3.4
python-pillow/Pillow
2,262
python-pillow__Pillow-2262
[ "2259" ]
789ac7aa720cdc81769eddf51cb9729cbb8ad0c1
diff --git a/PIL/Image.py b/PIL/Image.py --- a/PIL/Image.py +++ b/PIL/Image.py @@ -1994,8 +1994,8 @@ def _check_size(size): raise ValueError("Size must be a tuple") if len(size) != 2: raise ValueError("Size must be a tuple of length 2") - if size[0] <= 0 or size[1] <= 0: - raise ValueError("Width and Height must be > 0") + if size[0] < 0 or size[1] < 0: + raise ValueError("Width and Height must be => 0") return True
diff --git a/Tests/test_image.py b/Tests/test_image.py --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -256,7 +256,11 @@ def test_check_size(self): with self.assertRaises(ValueError): Image.new('RGB', (0,)) # Tuple too short with self.assertRaises(ValueError): - Image.new('RGB', (0,0)) # w,h <= 0 + Image.new('RGB', (-1,-1)) # w,h < 0 + + # this should pass with 0 sized images, #2259 + im = Image.new('L', (0, 0)) + self.assertEqual(im.size, (0, 0)) self.assertTrue(Image.new('RGB', (1,1))) # Should pass lists too diff --git a/Tests/test_image_access.py b/Tests/test_image_access.py --- a/Tests/test_image_access.py +++ b/Tests/test_image_access.py @@ -78,12 +78,25 @@ def check(self, mode, c=None): im.getpixel((0, 0)), c, "put/getpixel roundtrip failed for mode %s, color %s" % (mode, c)) + # Check 0 + im = Image.new(mode, (0, 0), None) + with self.assertRaises(IndexError): + im.putpixel((0, 0), c) + with self.assertRaises(IndexError): + im.getpixel((0, 0)) + # check initial color im = Image.new(mode, (1, 1), c) self.assertEqual( im.getpixel((0, 0)), c, "initial color failed for mode %s, color %s " % (mode, c)) + # Check 0 + im = Image.new(mode, (0, 0), c) + with self.assertRaises(IndexError): + im.getpixel((0, 0)) + + def test_basic(self): for mode in ("1", "L", "LA", "I", "I;16", "I;16B", "F", "P", "PA", "RGB", "RGBA", "RGBX", "CMYK", "YCbCr"): diff --git a/Tests/test_image_convert.py b/Tests/test_image_convert.py --- a/Tests/test_image_convert.py +++ b/Tests/test_image_convert.py @@ -19,6 +19,11 @@ def convert(im, mode): for mode in modes: convert(im, mode) + # Check 0 + im = Image.new(mode, (0,0)) + for mode in modes: + convert(im, mode) + def test_default(self): im = hopper("P") diff --git a/Tests/test_image_copy.py b/Tests/test_image_copy.py --- a/Tests/test_image_copy.py +++ b/Tests/test_image_copy.py @@ -1,5 +1,7 @@ from helper import unittest, PillowTestCase, hopper +from PIL import Image + import copy @@ -33,5 +35,12 @@ def test_copy(self): self.assertEqual(out.mode, im.mode) self.assertEqual(out.size, croppedSize) + def test_copy_zero(self): + im = Image.new('RGB', (0,0)) + out = im.copy() + self.assertEqual(out.mode, im.mode) + self.assertEqual(out.size, im.size) + + if __name__ == '__main__': unittest.main() diff --git a/Tests/test_image_crop.py b/Tests/test_image_crop.py --- a/Tests/test_image_crop.py +++ b/Tests/test_image_crop.py @@ -83,6 +83,23 @@ def test_crop_crash(self): img = img.crop(extents) img.load() + def test_crop_zero(self): + + im = Image.new('RGB', (0, 0), 'white') + + cropped = im.crop((0, 0, 0, 0)) + self.assertEqual(cropped.size, (0, 0)) + + cropped = im.crop((10, 10, 20, 20)) + self.assertEqual(cropped.size, (10, 10)) + self.assertEqual(cropped.getdata()[0], (0, 0, 0)) + + im = Image.new('RGB', (0, 0)) + + cropped = im.crop((10, 10, 20, 20)) + self.assertEqual(cropped.size, (10, 10)) + self.assertEqual(cropped.getdata()[2], (0, 0, 0)) + if __name__ == '__main__': diff --git a/Tests/test_image_resize.py b/Tests/test_image_resize.py --- a/Tests/test_image_resize.py +++ b/Tests/test_image_resize.py @@ -89,6 +89,14 @@ def test_endianness(self): # as separately resized channel self.assert_image_equal(ch, references[channels[i]]) + def test_enlarge_zero(self): + for f in [Image.NEAREST, Image.BOX, Image.BILINEAR, Image.HAMMING, + Image.BICUBIC, Image.LANCZOS]: + r = self.resize(Image.new('RGB', (0,0), "white"), (212, 195), f) + self.assertEqual(r.mode, "RGB") + self.assertEqual(r.size, (212, 195)) + self.assertEqual(r.getdata()[0], (0,0,0)) + class TestImageResize(PillowTestCase): diff --git a/Tests/test_image_rotate.py b/Tests/test_image_rotate.py --- a/Tests/test_image_rotate.py +++ b/Tests/test_image_rotate.py @@ -13,15 +13,24 @@ def rotate(im, mode, angle): self.assertEqual(out.mode, mode) if angle % 180 == 0: self.assertEqual(out.size, im.size) + elif im.size == (0, 0): + self.assertEqual(out.size, im.size) else: self.assertNotEqual(out.size, im.size) - for mode in "1", "P", "L", "RGB", "I", "F": + + + for mode in ("1", "P", "L", "RGB", "I", "F"): im = hopper(mode) rotate(im, mode, 45) - for angle in 0, 90, 180, 270: + + for angle in (0, 90, 180, 270): im = Image.open('Tests/images/test-card.png') rotate(im, im.mode, angle) + for angle in (0, 45, 90, 180, 270): + im = Image.new('RGB',(0,0)) + rotate(im, im.mode, angle) + if __name__ == '__main__': unittest.main()
Image of size zero is not getting initialized I want an image with zero size. I have a lot of use for it. ```py >>> from PIL import Image as im >>> import numpy as np >>> im.fromarray(np.empty((0, 0), dtype=np.uint8)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.4/dist-packages/PIL/Image.py", line 2187, in fromarray return frombuffer(mode, size, obj, "raw", rawmode, 0, 1) File "/usr/local/lib/python3.4/dist-packages/PIL/Image.py", line 2114, in frombuffer _check_size(size) File "/usr/local/lib/python3.4/dist-packages/PIL/Image.py", line 2001, in _check_size raise ValueError("Width and Height must be > 0") ValueError: Width and Height must be > 0 ``` This was working previously. But after this [commit](https://github.com/python-pillow/Pillow/commit/445451c0b9347b50e0f603db33f196e207de470d), in the latest version (i.e. 3.4.2) it is throwing an error. As @manthey points out in the commit, one can create a zero sized image by cropping an existing one. So this too should be allowed. Thanks.
2016-11-29T19:35:22Z
3.4
python-pillow/Pillow
2,115
python-pillow__Pillow-2115
[ "2064" ]
e5fd6d519e5b98584f7e23c3d7fb1783c45f3920
diff --git a/PIL/JpegImagePlugin.py b/PIL/JpegImagePlugin.py --- a/PIL/JpegImagePlugin.py +++ b/PIL/JpegImagePlugin.py @@ -682,13 +682,16 @@ def validate_qtables(qtables): o8(len(markers)) + marker) i += 1 + # "progressive" is the official name, but older documentation + # says "progression" + # FIXME: issue a warning if the wrong form is used (post-1.1.7) + progressive = info.get("progressive", False) or\ + info.get("progression", False) + # get keyword arguments im.encoderconfig = ( quality, - # "progressive" is the official name, but older documentation - # says "progression" - # FIXME: issue a warning if the wrong form is used (post-1.1.7) - "progressive" in info or "progression" in info, + progressive, info.get("smooth", 0), "optimize" in info, info.get("streamtype", 0), @@ -704,7 +707,7 @@ def validate_qtables(qtables): # channels*size, this is a value that's been used in a django patch. # https://github.com/matthewwithanm/django-imagekit/issues/50 bufsize = 0 - if "optimize" in info or "progressive" in info or "progression" in info: + if "optimize" in info or progressive: # keep sets quality to 0, but the actual value may be high. if quality >= 95 or quality == 0: bufsize = 2 * im.size[0] * im.size[1]
diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -227,12 +227,20 @@ def test_exif_gps_typeerror(self): def test_progressive_compat(self): im1 = self.roundtrip(hopper()) + self.assertFalse(im1.info.get("progressive")) + self.assertFalse(im1.info.get("progression")) + + im2 = self.roundtrip(hopper(), progressive=0) + im3 = self.roundtrip(hopper(), progression=0) # compatibility + self.assertFalse(im2.info.get("progressive")) + self.assertFalse(im2.info.get("progression")) + self.assertFalse(im3.info.get("progressive")) + self.assertFalse(im3.info.get("progression")) + im2 = self.roundtrip(hopper(), progressive=1) im3 = self.roundtrip(hopper(), progression=1) # compatibility self.assert_image_equal(im1, im2) self.assert_image_equal(im1, im3) - self.assertFalse(im1.info.get("progressive")) - self.assertFalse(im1.info.get("progression")) self.assertTrue(im2.info.get("progressive")) self.assertTrue(im2.info.get("progression")) self.assertTrue(im3.info.get("progressive"))
unintuitive save properties > **progressive** > If present, indicates that this image should be stored as a progressive JPEG file. It is not completely obvious that `progressive = False` evaluates to it being set. I guess it's difficult to change this whilst keeping backwards compatibility. (I doubt someone passes `progressive = False` with the intention to enable it.)
2016-09-17T10:14:27Z
3.3
python-pillow/Pillow
2,131
python-pillow__Pillow-2131
[ "2037", "2037" ]
4129c6e0ebc97f7632458a634017c63d675302eb
diff --git a/PIL/ImageCms.py b/PIL/ImageCms.py --- a/PIL/ImageCms.py +++ b/PIL/ImageCms.py @@ -162,8 +162,11 @@ def __init__(self, profile): self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) + elif isinstance(profile, _imagingcms.CmsProfile): + self._set(profile) else: - self._set(profile) # assume it's already a profile + raise TypeError("Invalid type for Profile") + def _set(self, profile, filename=None): self.profile = profile
diff --git a/Tests/test_imagecms.py b/Tests/test_imagecms.py --- a/Tests/test_imagecms.py +++ b/Tests/test_imagecms.py @@ -321,5 +321,17 @@ def truncate_tuple(tuple_or_float): self.assertEqual(p.viewing_condition, 'Reference Viewing Condition in IEC 61966-2-1') self.assertEqual(p.xcolor_space, 'RGB ') + def test_profile_typesafety(self): + """ Profile init type safety + + prepatch, these would segfault, postpatch they should emit a typeerror + """ + + with self.assertRaises(TypeError): + ImageCms.ImageCmsProfile(0).tobytes() + with self.assertRaises(TypeError): + ImageCms.ImageCmsProfile(1).tobytes() + + if __name__ == '__main__': unittest.main()
segfault: ImageCmsProfile ``` Python >>> from PIL import ImageCms >>> ImageCms.ImageCmsProfile(0).tobytes() python: cmsio0.c:1301: cmsSaveProfileToIOhandler: Assertion '(hProfile != ((void *)0))' failed. >>> ImageCms.ImageCmsProfile(1).tobytes() Segmentation fault ``` segfault: ImageCmsProfile ``` Python >>> from PIL import ImageCms >>> ImageCms.ImageCmsProfile(0).tobytes() python: cmsio0.c:1301: cmsSaveProfileToIOhandler: Assertion '(hProfile != ((void *)0))' failed. >>> ImageCms.ImageCmsProfile(1).tobytes() Segmentation fault ```
It also accepts `None` and returns a 132-bytes ICC header. Looks like any arbitrary python object is getting passed into cms_profile_tobytes, where it's cast to a CmsProfileObject and then used. Looks like we need some type checks in the python level at ImageCmsProfile.**init** and in the c layer in cms_profile_tobytes. ``` def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isStringType(profile): self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) else: # UNDONE -- could be anything, and is passed into _tobytes directly self._set(profile) # assume it's already a profile ``` ``` static PyObject* cms_profile_tobytes(PyObject* self, PyObject* args) { char *pProfile =NULL; cmsUInt32Number nProfile; PyObject* CmsProfile; cmsHPROFILE *profile; PyObject* ret; if (!PyArg_ParseTuple(args, "O", &CmsProfile)){ return NULL; } /* UNDONE -- need to check type and success here. This can be any python type, and could very well be something else. */ profile = ((CmsProfileObject*)CmsProfile)->profile; ``` It also accepts `None` and returns a 132-bytes ICC header. Looks like any arbitrary python object is getting passed into cms_profile_tobytes, where it's cast to a CmsProfileObject and then used. Looks like we need some type checks in the python level at ImageCmsProfile.**init** and in the c layer in cms_profile_tobytes. ``` def __init__(self, profile): """ :param profile: Either a string representing a filename, a file like object containing a profile or a low-level profile object """ if isStringType(profile): self._set(core.profile_open(profile), profile) elif hasattr(profile, "read"): self._set(core.profile_frombytes(profile.read())) else: # UNDONE -- could be anything, and is passed into _tobytes directly self._set(profile) # assume it's already a profile ``` ``` static PyObject* cms_profile_tobytes(PyObject* self, PyObject* args) { char *pProfile =NULL; cmsUInt32Number nProfile; PyObject* CmsProfile; cmsHPROFILE *profile; PyObject* ret; if (!PyArg_ParseTuple(args, "O", &CmsProfile)){ return NULL; } /* UNDONE -- need to check type and success here. This can be any python type, and could very well be something else. */ profile = ((CmsProfileObject*)CmsProfile)->profile; ```
2016-09-26T13:22:05Z
3.3
python-pillow/Pillow
2,103
python-pillow__Pillow-2103
[ "2098" ]
6e7553fb0f12025306b2819b9b842adf6b598b2e
diff --git a/PIL/GifImagePlugin.py b/PIL/GifImagePlugin.py --- a/PIL/GifImagePlugin.py +++ b/PIL/GifImagePlugin.py @@ -351,34 +351,38 @@ def _save(im, fp, filename, save_all=False): previous = None first_frame = None - for im_frame in ImageSequence.Iterator(im): - im_frame = _convert_mode(im_frame) - - # To specify duration, add the time in milliseconds to getdata(), - # e.g. getdata(im_frame, duration=1000) - if not previous: - # global header - first_frame = getheader(im_frame, palette, im.encoderinfo)[0] - first_frame += getdata(im_frame, (0, 0), **im.encoderinfo) - else: - if first_frame: - for s in first_frame: - fp.write(s) - first_frame = None - - # delta frame - delta = ImageChops.subtract_modulo(im_frame, previous.copy()) - bbox = delta.getbbox() - - if bbox: - # compress difference - for s in getdata(im_frame.crop(bbox), - bbox[:2], **im.encoderinfo): - fp.write(s) + append_images = im.encoderinfo.get("append_images", []) + for imSequence in [im]+append_images: + for im_frame in ImageSequence.Iterator(imSequence): + encoderinfo = im.encoderinfo.copy() + im_frame = _convert_mode(im_frame) + + # To specify duration, add the time in milliseconds to getdata(), + # e.g. getdata(im_frame, duration=1000) + if not previous: + # global header + first_frame = getheader(im_frame, palette, encoderinfo)[0] + first_frame += getdata(im_frame, (0, 0), **encoderinfo) else: - # FIXME: what should we do in this case? - pass - previous = im_frame + if first_frame: + for s in first_frame: + fp.write(s) + first_frame = None + + # delta frame + delta = ImageChops.subtract_modulo(im_frame, previous.copy()) + bbox = delta.getbbox() + + if bbox: + # compress difference + encoderinfo['include_color_table'] = True + for s in getdata(im_frame.crop(bbox), + bbox[:2], **encoderinfo): + fp.write(s) + else: + # FIXME: what should we do in this case? + pass + previous = im_frame if first_frame: save_all = False if not save_all: @@ -455,7 +459,7 @@ def _get_local_header(fp, im, offset, flags): fp.write(b"!" + o8(249) + # extension intro o8(4) + # length - o8(transparency_flag) + # transparency info present + o8(transparency_flag) + # packed fields o16(duration) + # duration o8(transparency) + # transparency index o8(0)) @@ -476,13 +480,27 @@ def _get_local_header(fp, im, offset, flags): o8(1) + o16(number_of_loops) + # number of loops o8(0)) + include_color_table = im.encoderinfo.get('include_color_table') + if include_color_table: + try: + palette = im.encoderinfo["palette"] + except KeyError: + palette = None + palette_bytes = _get_palette_bytes(im, palette, im.encoderinfo)[0] + color_table_size = _get_color_table_size(palette_bytes) + if color_table_size: + flags = flags | 128 # local color table flag + flags = flags | color_table_size + fp.write(b"," + o16(offset[0]) + # offset o16(offset[1]) + o16(im.size[0]) + # size o16(im.size[1]) + - o8(flags) + # flags - o8(8)) # bits + o8(flags)) # flags + if include_color_table and color_table_size: + fp.write(_get_header_palette(palette_bytes)) + fp.write(o8(8)) # bits def _save_netpbm(im, fp, filename): @@ -550,31 +568,25 @@ def _get_used_palette_colors(im): return used_palette_colors +def _get_color_table_size(palette_bytes): + # calculate the palette size for the header + import math + color_table_size = int(math.ceil(math.log(len(palette_bytes)//3, 2)))-1 + if color_table_size < 0: + color_table_size = 0 + return color_table_size -def getheader(im, palette=None, info=None): - """Return a list of strings representing a GIF header""" - - # Header Block - # http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp +def _get_header_palette(palette_bytes): + color_table_size = _get_color_table_size(palette_bytes) - version = b"87a" - for extensionKey in ["transparency", "duration", "loop", "comment"]: - if info and extensionKey in info: - if ((extensionKey == "duration" and info[extensionKey] == 0) or - (extensionKey == "comment" and not (1 <= len(info[extensionKey]) <= 255))): - continue - version = b"89a" - break - else: - if im.info.get("version") == "89a": - version = b"89a" - - header = [ - b"GIF"+version + # signature + version - o16(im.size[0]) + # canvas width - o16(im.size[1]) # canvas height - ] + # add the missing amount of bytes + # the palette has to be 2<<n in size + actual_target_size_diff = (2 << color_table_size) - len(palette_bytes)//3 + if actual_target_size_diff > 0: + palette_bytes += o8(0) * 3 * actual_target_size_diff + return palette_bytes +def _get_palette_bytes(im, palette, info): if im.mode == "P": if palette and isinstance(palette, bytes): source_palette = palette[:768] @@ -617,15 +629,38 @@ def getheader(im, palette=None, info=None): if not palette_bytes: palette_bytes = source_palette + return palette_bytes, used_palette_colors + +def getheader(im, palette=None, info=None): + """Return a list of strings representing a GIF header""" + + # Header Block + # http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp + + version = b"87a" + for extensionKey in ["transparency", "duration", "loop", "comment"]: + if info and extensionKey in info: + if ((extensionKey == "duration" and info[extensionKey] == 0) or + (extensionKey == "comment" and not (1 <= len(info[extensionKey]) <= 255))): + continue + version = b"89a" + break + else: + if im.info.get("version") == "89a": + version = b"89a" + + header = [ + b"GIF"+version + # signature + version + o16(im.size[0]) + # canvas width + o16(im.size[1]) # canvas height + ] + + palette_bytes, used_palette_colors = _get_palette_bytes(im, palette, info) # Logical Screen Descriptor - # calculate the palette size for the header - import math - color_table_size = int(math.ceil(math.log(len(palette_bytes)//3, 2)))-1 - if color_table_size < 0: - color_table_size = 0 + color_table_size = _get_color_table_size(palette_bytes) # size of global color table + global color table flag - header.append(o8(color_table_size + 128)) + header.append(o8(color_table_size + 128)) # packed fields # background + reserved/aspect if info and "background" in info: background = info["background"] @@ -640,14 +675,8 @@ def getheader(im, palette=None, info=None): header.append(o8(background) + o8(0)) # end of Logical Screen Descriptor - # add the missing amount of bytes - # the palette has to be 2<<n in size - actual_target_size_diff = (2 << color_table_size) - len(palette_bytes)//3 - if actual_target_size_diff > 0: - palette_bytes += o8(0) * 3 * actual_target_size_diff - # Header + Logical Screen Descriptor + Global Color Table - header.append(palette_bytes) + header.append(_get_header_palette(palette_bytes)) return header, used_palette_colors
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -306,6 +306,24 @@ def test_version(self): reread = Image.open(out) self.assertEqual(reread.info["version"], b"GIF87a") + def test_append_images(self): + out = self.tempfile('temp.gif') + + # Test appending single frame images + im = Image.new('RGB', (100, 100), '#f00') + ims = [Image.new('RGB', (100, 100), color) for color in ['#0f0', '#00f']] + im.save(out, save_all=True, append_images=ims) + + reread = Image.open(out) + self.assertEqual(reread.n_frames, 3) + + # Tests appending single and multiple frame images + im = Image.open("Tests/images/dispose_none.gif") + ims = [Image.open("Tests/images/dispose_prev.gif")] + im.save(out, save_all=True, append_images=ims) + + reread = Image.open(out) + self.assertEqual(reread.n_frames, 10) if __name__ == '__main__': unittest.main()
Create an animated GIF from scratch Can Pillow create animated GIFs from scratch at all? Like, having a series of 10 images of the same size, can I turn them into frames and save them as an animated GIF?
Yes you can, check this package https://gist.github.com/jonschoning/7216290 . No offence, but you are practically writing the GIF by hand byte by byte. I could do that as well, but I'd rather have an abstraction over the format of GIF files, that's why I'm using an imaging library. Hi. There isn't a simple way to do that at the moment. I'd be interested in putting together a PR, if anyone can think of a good API to use. To solve your immediate problem, I have copied and modified GifImagePlugin's `_save` method to put together an example script for creating an animated GIF. This could be better, but hopefully you will find it helpful. ``` from PIL import Image, ImageFile, ImageChops from PIL.GifImagePlugin import _imaging_gif, RAWMODE, _convert_mode, getheader, getdata, get_interlace, _get_local_header def save_sequence(ims, filename): im = ims[0] fp = open(filename, 'wb') if hasattr(im, 'encoderinfo'): im.encoderinfo.update(im.info) if _imaging_gif: # call external driver try: _imaging_gif.save(im, fp, filename) return except IOError: pass # write uncompressed file if im.mode in RAWMODE: im_out = im.copy() else: im_out = _convert_mode(im, True) # header if hasattr(im, 'encoderinfo'): try: palette = im.encoderinfo["palette"] except KeyError: palette = None im.encoderinfo["optimize"] = im.encoderinfo.get("optimize", True) else: palette = None im.encoderinfo = {} save_all = True if save_all: previous = None first_frame = None for im_frame in ims: im_frame = _convert_mode(im_frame) # To specify duration, add the time in milliseconds to getdata(), # e.g. getdata(im_frame, duration=1000) if not previous: # global header first_frame = getheader(im_frame, palette, im.encoderinfo)[0] first_frame += getdata(im_frame, (0, 0), **im.encoderinfo) else: if first_frame: for s in first_frame: fp.write(s) first_frame = None # delta frame delta = ImageChops.subtract_modulo(im_frame, previous.copy()) bbox = delta.getbbox() if bbox: # compress difference for s in getdata(im_frame.crop(bbox), bbox[:2], **im.encoderinfo): fp.write(s) else: # FIXME: what should we do in this case? pass previous = im_frame if first_frame: save_all = False if not save_all: header = getheader(im_out, palette, im.encoderinfo)[0] for s in header: fp.write(s) flags = 0 if get_interlace(im): flags = flags | 64 # local image header _get_local_header(fp, im, (0, 0), flags) im_out.encoderconfig = (8, get_interlace(im)) ImageFile._save(im_out, fp, [("gif", (0, 0)+im.size, 0, RAWMODE[im_out.mode])]) fp.write(b"\0") # end of image data fp.write(b";") # end of file if hasattr(fp, "flush"): fp.flush() ims = [Image.new('RGB', (100, 100), hex) for hex in ['#f00', '#0f0','#0ff','#ff0','#000','#fff','#f0f']] save_sequence(ims, 'test.gif') ``` You could take a look at Wand, which is another binding to ImageMagick. Here's an example of what creating a GIF looks like there (although the implementation is buggy so I've had to abandon that library): https://github.com/dahlia/wand/issues/300#issue-166542295 I'd be very thankful if you could make that PR, I'm very interested in this feature. Okay, I've created a PR. Please provide any feedback you might have.
2016-09-04T11:17:44Z
3.3
python-pillow/Pillow
1,988
python-pillow__Pillow-1988
[ "1910" ]
8e7f0cb192aa488f6b4622e71ec0ba9eb9a592c0
diff --git a/PIL/TiffImagePlugin.py b/PIL/TiffImagePlugin.py --- a/PIL/TiffImagePlugin.py +++ b/PIL/TiffImagePlugin.py @@ -544,8 +544,7 @@ def _setitem(self, tag, value, legacy_api): self.tagtype[tag] = 2 if self.tagtype[tag] == 7 and bytes is not str: - values = [value.encode("ascii", 'replace') if isinstance(value, str) else value - for value in values] + values = [value.encode("ascii", 'replace') if isinstance(value, str) else value] values = tuple(info.cvt_enum(value) for value in values) @@ -604,8 +603,7 @@ def _register_basic(idx_fmt_name): @_register_loader(1, 1) # Basic type, except for the legacy API. def load_byte(self, data, legacy_api=True): - return (data if legacy_api else - tuple(map(ord, data) if bytes is str else data)) + return data @_register_writer(1) # Basic type, except for the legacy API. def write_byte(self, data): diff --git a/PIL/TiffTags.py b/PIL/TiffTags.py --- a/PIL/TiffTags.py +++ b/PIL/TiffTags.py @@ -48,11 +48,21 @@ def lookup(tag): # # id: (Name, Type, Length, enum_values) # +# The length here differs from the length in the tiff spec. For +# numbers, the tiff spec is for the number of fields returned. We +# agree here. For string-like types, the tiff spec uses the length of +# field in bytes. In Pillow, we are using the number of expected +# fields, in general 1 for string-like types. + +BYTE = 1 ASCII = 2 SHORT = 3 LONG = 4 RATIONAL = 5 +UNDEFINED = 7 +SIGNED_RATIONAL = 10 +DOUBLE = 12 TAGS_V2 = { @@ -128,8 +138,8 @@ def lookup(tag): 338: ("ExtraSamples", SHORT, 0), 339: ("SampleFormat", SHORT, 0), - 340: ("SMinSampleValue", 12, 0), - 341: ("SMaxSampleValue", 12, 0), + 340: ("SMinSampleValue", DOUBLE, 0), + 341: ("SMaxSampleValue", DOUBLE, 0), 342: ("TransferRange", SHORT, 6), # obsolete JPEG tags @@ -152,34 +162,34 @@ def lookup(tag): # FIXME add more tags here 34665: ("ExifIFD", SHORT, 1), - 34675: ('ICCProfile', 7, 0), - 34853: ('GPSInfoIFD', 1, 1), + 34675: ('ICCProfile', UNDEFINED, 1), + 34853: ('GPSInfoIFD', BYTE, 1), # MPInfo - 45056: ("MPFVersion", 7, 1), + 45056: ("MPFVersion", UNDEFINED, 1), 45057: ("NumberOfImages", LONG, 1), - 45058: ("MPEntry", 7, 1), - 45059: ("ImageUIDList", 7, 0), + 45058: ("MPEntry", UNDEFINED, 1), + 45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check 45060: ("TotalFrames", LONG, 1), 45313: ("MPIndividualNum", LONG, 1), 45569: ("PanOrientation", LONG, 1), 45570: ("PanOverlap_H", RATIONAL, 1), 45571: ("PanOverlap_V", RATIONAL, 1), 45572: ("BaseViewpointNum", LONG, 1), - 45573: ("ConvergenceAngle", 10, 1), + 45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1), 45574: ("BaselineLength", RATIONAL, 1), - 45575: ("VerticalDivergence", 10, 1), - 45576: ("AxisDistance_X", 10, 1), - 45577: ("AxisDistance_Y", 10, 1), - 45578: ("AxisDistance_Z", 10, 1), - 45579: ("YawAngle", 10, 1), - 45580: ("PitchAngle", 10, 1), - 45581: ("RollAngle", 10, 1), + 45575: ("VerticalDivergence", SIGNED_RATIONAL, 1), + 45576: ("AxisDistance_X", SIGNED_RATIONAL, 1), + 45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1), + 45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1), + 45579: ("YawAngle", SIGNED_RATIONAL, 1), + 45580: ("PitchAngle", SIGNED_RATIONAL, 1), + 45581: ("RollAngle", SIGNED_RATIONAL, 1), 50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}), 50780: ("BestQualityScale", RATIONAL, 1), 50838: ("ImageJMetaDataByteCounts", LONG, 1), - 50839: ("ImageJMetaData", 7, 1) + 50839: ("ImageJMetaData", UNDEFINED, 1) } # Legacy Tags structure
diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -287,7 +287,7 @@ def test_load_byte(self): ifd = TiffImagePlugin.ImageFileDirectory_v2() data = b"abc" ret = ifd.load_byte(data, legacy_api) - self.assertEqual(ret, b"abc" if legacy_api else (97, 98, 99)) + self.assertEqual(ret, b"abc") def test_load_string(self): ifd = TiffImagePlugin.ImageFileDirectory_v2() diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py --- a/Tests/test_file_tiff_metadata.py +++ b/Tests/test_file_tiff_metadata.py @@ -175,7 +175,7 @@ def test_iccprofile(self): im.save(out) reloaded = Image.open(out) - self.assert_(type(im.info['icc_profile']) is not type(tuple)) + self.assert_(type(im.info['icc_profile']) is not tuple) self.assertEqual(im.info['icc_profile'], reloaded.info['icc_profile']) def test_iccprofile_binary(self): @@ -186,6 +186,16 @@ def test_iccprofile_binary(self): self.assertEqual(im.tag_v2.tagtype[34675], 1) self.assertTrue(im.info['icc_profile']) + def test_iccprofile_save_png(self): + im = Image.open('Tests/images/hopper.iccprofile.tif') + outfile = self.tempfile('temp.png') + im.save(outfile) + + def test_iccprofile_binary_save_png(self): + im = Image.open('Tests/images/hopper.iccprofile_binary.tif') + outfile = self.tempfile('temp.png') + im.save(outfile) + def test_exif_div_zero(self): im = hopper() info = TiffImagePlugin.ImageFileDirectory_v2()
Tuple of integers in info['icc_profile'] Test image: http://ucarecdn.com/265ac6b0-2a1f-4128-b198-ee5159581771/ Pillow 3.2 ``` python >>> icc = Image.open('test.tiff').info['icc_profile'] >>> print repr(icc[:30]) (0, 8, 128, 112, 65, 68, 66, 69, 2, 16, 0, 0, 112, 114, 116, 114, 67, 77, 89, 75, 76, 97, 98, 32, 7, 208, 0, 7, 0, 26) ``` Pillow 2.9 ``` python >>> icc = Image.open('test.tiff').info['icc_profile'] >>> print repr(icc[:30]) '\x00\x08\x80pADBE\x02\x10\x00\x00prtrCMYKLab \x07\xd0\x00\x07\x00\x1a' ```
Currently, I use the following code to extract ICC profile in Pillow 3.2: ``` python def _extract_icc(self): icc = self.image.info.pop('icc_profile', None) if isinstance(icc, tuple): try: icc = "".join(icc) except TypeError: icc = ''.join(map(chr, icc)) return icc ``` While for Pillow 2.9 the following was enough: ``` python icc = self.image.info.pop('icc_profile', None) ``` Related to #1831? Really I don't know. How I understand, #1831 fixes tuple of bytestrings instead of bytestring. In this case, Pillow returns a tuple of ints.
2016-06-26T11:14:28Z
3.2
python-pillow/Pillow
1,985
python-pillow__Pillow-1985
[ "1593" ]
4a63e9c384d3d581be853fc93bb6445a2d7afe32
diff --git a/PIL/ImagePalette.py b/PIL/ImagePalette.py --- a/PIL/ImagePalette.py +++ b/PIL/ImagePalette.py @@ -38,7 +38,7 @@ class ImagePalette(object): def __init__(self, mode="RGB", palette=None, size=0): self.mode = mode self.rawmode = None # if set, palette contains raw data - self.palette = palette or list(range(256))*len(self.mode) + self.palette = palette or bytearray(range(256))*len(self.mode) self.colors = {} self.dirty = None if ((size == 0 and len(self.mode)*256 != len(self.palette)) or @@ -98,7 +98,7 @@ def getcolor(self, color): except KeyError: # allocate new color slot if isinstance(self.palette, bytes): - self.palette = [int(x) for x in self.palette] + self.palette = bytearray(self.palette) index = len(self.colors) if index >= 256: raise ValueError("cannot allocate more than 256 colors")
diff --git a/Tests/images/chi.gif b/Tests/images/chi.gif new file mode 100644 Binary files /dev/null and b/Tests/images/chi.gif differ diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -52,6 +52,13 @@ def test_removed_methods(self): self.assertRaises(Exception, lambda: draw.setink(0)) self.assertRaises(Exception, lambda: draw.setfill(0)) + def test_valueerror(self): + im = Image.open("Tests/images/chi.gif") + + draw = ImageDraw.Draw(im) + draw.line(((0, 0)), fill=(0, 0, 0)) + del draw + def test_mode_mismatch(self): im = hopper("RGB").copy()
Changed int conversion in ImagePalette to ord for Python 2 Error reported in #1592
I'm not convinced that this is the right approach yet. There's got to be something screwy with the palette, because if it was just an bytes/int conversion issue, then we'd likely have run across this before. The code's been in there since the conversion to py3. What's the character that's throwing it off? How is it encoded in the palette? The palette string is - ``` b'\x00\x01\x002313424635746857968979:8:;9;=:<>;=?<>@=?@>@A?AB@ACACEBDFCEGDFHEGIFHIGIJHJKIJLJLNKMOLNPMOQNPROQSPRTQSTRTUSUVTVWUVXUWYVY[XZ\\Y[]Z\\^[]_\\^`]_a^`b_ac`bdacebdecefdfgeghfhighjgikhjlikmjlnkmolnpmoqnqsprtqsurtvsuwtvxuwyvxzwy{xz|y{}z|~{}\x7f|~\x80}\x7f\x81~x\x8a:\x80\x82\x7f\x81\x83\x80z\x8c<\x82\x84\x81\x83\x85\x82\x84\x86\x83}\x8f?\x85\x87\x84\x86\x88\x85\x87\x89\x86\x88\x8a\x87\x89\x8b\x88\x83\x94D\x8a\x8c\x89\x8b\x8d\x8a\x8c\x8e\x8b\x8d\x8f\x8c\x8e\x90\x8d\x8f\x91\x8e\x90\x92\x8f\x91\x93\x90\x92\x94\x91\x93\x95\x92\x94\x96\x93\x95\x97\x94\x96\x98\x95\x97\x99\x96\x98\x9a\x97\x9a\x9b\x98\x9b\x9d\x99\x9c\x9e\x9b\x9d\x9f\x9c\x9e\xa0\x9d\x9f\xa1\x9e\xa0\xa2\x9f\x9c\xaaf\xa1\xa3\xa0\xa2\xa4\xa1\xa3\xa5\xa2\xa4\xa6\xa3\xa5\xa7\xa4\xa6\xa8\xa5\xa7\xa9\xa6\xa8\xaa\xa7\xa9\xab\xa8\xaa\xac\xa9\xab\xad\xaa\xa5\xbb<\xac\xae\xab\xa6\xbc=\xad\xaf\xac\xa7\xbd>\xae\xb0\xad\xa8\xbe?\xb0\xb2\xae\xb1\xb3\xaf\xb2\xb4\xb1\xb3\xb5\xb2\xb4\xb6\xb3\xb5\xb7\xb4\xb6\xb8\xb5\xb7\xb9\xb6\xb8\xba\xb7\xb9\xbb\xb8\xb0\xc8W\xba\xbc\xb9\xbb\xbd\xba\xb1\xcdD\xbc\xbe\xbb\xb2\xceE\xbd\xbf\xbc\xb4\xcfF\xbe\xc1\xbd\xb5\xd0G\xb3\xd0O\xc0\xc2\xbe\xb5\xd1P\xc1\xc3\xbf\xb6\xd2Q\xc2\xc4\xc1\xb7\xd3R\xbc\xd2R\xc3\xc5\xc2\xbe\xd3S\xc4\xc6\xc3\xbc\xd3[\xc5\xc7\xc4\xbd\xd4\\\xc6\xc8\xc5\xbe\xd5]\xc7\xc9\xc6\xbe\xd6e\xc8\xca\xc7\xc9\xcb\xc8\xbf\xd8f\xca\xcc\xc9\xc0\xd9g\xbf\xd9n\xc9\xd1\xa6\xc6\xd8o\xc0\xdao\xcb\xce\xca\xcd\xcf\xcb\xc7\xdap\xc5\xdav\xce\xd0\xcc\xcf\xd1\xce\xd0\xd2\xcf\xc9\xddz\xc7\xdd\x80\xd1\xd3\xd0\xc8\xde\x81\xd2\xd4\xd1\xc9\xdf\x82\xcf\xde\x82\xd3\xd5\xd2\xd0\xdf\x83\xd4\xd6\xd3\xd5\xd7\xd4\xd1\xdf\x98\xd6\xd8\xd5\xd8\xda\xd6\xd1\xe4\x94\xd9\xdb\xd7\xd8\xe3\x96\xd2\xe5\x95\xda\xdc\xd9\xd7\xe4\x9d\xdb\xdd\xda\xdc\xde\xdb\xd8\xe6\x9e\xdd\xdf\xdc\xd9\xe7\x9f\xde\xe0\xdd\xd8\xe8\xa6\xdf\xe1\xde\xd9\xe9\xa7\xe0\xe2\xdf\xda\xea\xa8\xde\xe9\xaf\xe1\xe4\xe0\xe3\xe5\xe1\xe4\xe6\xe3\xe5\xe7\xe4\xe6\xe8\xe5\xe7\xe9\xe6\xe8\xea\xe7\xe7\xef\xc3\xe9\xeb\xe8\xe8\xf0\xc4\xea\xec\xe9\xeb\xee\xea\xed\xef\xeb\xee\xf0\xed\xef\xf1\xee\xf0\xf2\xef\xf1\xf3\xf0\xf2\xf4\xf1\xf3\xf5\xf2\xf4\xf7\xf3\xf6\xf8\xf4\xf7\xf9\xf6\xf8\xfa\xf7\xf9\xfb\xf8\xfa\xfc\xf9\xfb\xfd\xfa\xfc\xff\xfb\xfe\xff\xfc\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' ``` It looks to me like the '\x00' character is being rendered as '' in Python 2, but converted by int by Python 3. So, any palette that contains black (#000000) should error out in python 2.x with PIL from 2012 through current master.
2016-06-25T13:59:28Z
3.2
python-pillow/Pillow
1,647
python-pillow__Pillow-1647
[ "1645" ]
d6bbe295323bf31dbc89d8bd2dcf3644309ad994
diff --git a/PIL/ImageDraw.py b/PIL/ImageDraw.py --- a/PIL/ImageDraw.py +++ b/PIL/ImageDraw.py @@ -241,9 +241,9 @@ def _multiline_split(self, text): return text.split(split_character) - def text(self, xy, text, fill=None, font=None, anchor=None): + def text(self, xy, text, fill=None, font=None, anchor=None, *args, **kwargs): if self._multiline_check(text): - return self.multiline_text(xy, text, fill, font, anchor) + return self.multiline_text(xy, text, fill, font, anchor, *args, **kwargs) ink, fill = self._getink(fill) if font is None: @@ -288,9 +288,9 @@ def multiline_text(self, xy, text, fill=None, font=None, anchor=None, ## # Get the size of a given string, in pixels. - def textsize(self, text, font=None): + def textsize(self, text, font=None, *args, **kwargs): if self._multiline_check(text): - return self.multiline_textsize(text, font) + return self.multiline_textsize(text, font, *args, **kwargs) if font is None: font = self.getfont()
diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -121,6 +121,7 @@ def test_textsize_equal(self): size = draw.textsize(txt, ttf) draw.text((10, 10), txt, font=ttf) draw.rectangle((10, 10, 10 + size[0], 10 + size[1])) + del draw target = 'Tests/images/rectangle_surrounding_text.png' target_img = Image.open(target) @@ -159,12 +160,20 @@ def test_render_multiline_text(self): self.assert_image_similar(im, target_img, .5) + # Test that text() can pass on additional arguments + # to multiline_text() + draw.text((0, 0), TEST_TEXT, fill=None, font=ttf, anchor=None, + spacing=4, align="left") + draw.text((0, 0), TEST_TEXT, None, ttf, None, 4, "left") + del draw + # Test align center and right for align, ext in {"center": "_center", "right": "_right"}.items(): im = Image.new(mode='RGB', size=(300, 100)) draw = ImageDraw.Draw(im) draw.multiline_text((0, 0), TEST_TEXT, font=ttf, align=align) + del draw target = 'Tests/images/multiline_text'+ext+'.png' target_img = Image.open(target) @@ -191,6 +200,12 @@ def test_multiline_size(self): self.assertEqual(draw.textsize(TEST_TEXT, font=ttf), draw.multiline_textsize(TEST_TEXT, font=ttf)) + # Test that textsize() can pass on additional arguments + # to multiline_textsize() + draw.textsize(TEST_TEXT, font=ttf, spacing=4) + draw.textsize(TEST_TEXT, ttf, 4) + del draw + def test_multiline_width(self): ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE) im = Image.new(mode='RGB', size=(300, 100)) @@ -199,6 +214,7 @@ def test_multiline_width(self): self.assertEqual(draw.textsize("longest line", font=ttf)[0], draw.multiline_textsize("longest line\nline", font=ttf)[0]) + del draw def test_multiline_spacing(self): ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE) @@ -206,6 +222,7 @@ def test_multiline_spacing(self): im = Image.new(mode='RGB', size=(300, 100)) draw = ImageDraw.Draw(im) draw.multiline_text((0, 0), TEST_TEXT, font=ttf, spacing=10) + del draw target = 'Tests/images/multiline_text_spacing.png' target_img = Image.open(target) @@ -229,6 +246,7 @@ def test_rotated_transposed_font(self): # Rotated font draw.font = transposed_font box_size_b = draw.textsize(word) + del draw # Check (w,h) of box a is (h,w) of box b self.assertEqual(box_size_a[0], box_size_b[1]) @@ -251,6 +269,7 @@ def test_unrotated_transposed_font(self): # Rotated font draw.font = transposed_font box_size_b = draw.textsize(word) + del draw # Check boxes a and b are same size self.assertEqual(box_size_a, box_size_b) @@ -346,6 +365,7 @@ def test_default_font(self): # Act default_font = ImageFont.load_default() draw.text((10, 10), txt, font=default_font) + del draw # Assert self.assert_image_equal(im, target_img)
Provide additional keyword args for ImageDraw.text(...) method for multiline text The check for `if self._multiline_check(text):` inside of the `ImageDraw.text(...)` method [1] is great, but if True, it goes to the next line `return self.multiline_text(xy, text, fill, font, anchor)` and doesn't allow the user to pass important keyword args to the `multiline_text(...)` function like **align** and **spacing**. Instead, why not do something like: ``` py def text(self, xy, text, fill=None, font=None, anchor=None, **kwargs): """:param kwargs: additional args to pass to multiline_text if the text is multiline""" if self._multiline_check(text): return self.multiline_text(xy, text, fill, font, anchor, **kwargs) ``` Then I can call the `.text(...)` function with those additional params: ``` py draw = ImageDraw.Draw(myImage) draw.text((0,0), 'hello world', align='left', spacing=5) ``` This would be a passive change to the current `.text(...)` method call. [1] https://github.com/python-pillow/Pillow/blob/master/PIL/ImageDraw.py#L245
2016-01-05T23:46:23Z
3.1
python-pillow/Pillow
1,686
python-pillow__Pillow-1686
[ "1685" ]
3d6e137ff274ab14cedf89d4e54e65095ae89f3d
diff --git a/PIL/ImageSequence.py b/PIL/ImageSequence.py --- a/PIL/ImageSequence.py +++ b/PIL/ImageSequence.py @@ -35,8 +35,7 @@ def __init__(self, im): def __getitem__(self, ix): try: - if ix: - self.im.seek(ix) + self.im.seek(ix) return self.im except EOFError: raise IndexError # end of sequence
diff --git a/Tests/test_imagesequence.py b/Tests/test_imagesequence.py --- a/Tests/test_imagesequence.py +++ b/Tests/test_imagesequence.py @@ -44,6 +44,17 @@ def test_libtiff(self): self._test_multipage_tiff() TiffImagePlugin.READ_LIBTIFF = False + def test_consecutive(self): + im = Image.open('Tests/images/multipage.tiff') + firstFrame = None + for frame in ImageSequence.Iterator(im): + if firstFrame == None: + firstFrame = frame.copy() + pass + for frame in ImageSequence.Iterator(im): + self.assert_image_equal(frame, firstFrame) + break + if __name__ == '__main__': unittest.main()
Repeated looping over image stack shows last frame in place of first frame When looping through the frames in an animation or TIFF stack with `ImageSequence.Iterator`, the frame pointer is not reset for the first frame. Consequently, if the loop is run through a second time the final frame is shown again instead of the first frame. ### Demo Code ``` python from PIL import Image, ImageSequence import os # Make a test image os.system(( "convert -depth 8 -size 1x1 xc:'rgb(100,100,100)' xc:'rgb(121,121,121)'" " xc:'rgb(142,142,142)' xc:'rgb(163,163,163)' image.tif" )) # Open the image im = Image.open('image.tif') # Run through the image print('First run') for frame in ImageSequence.Iterator(im): print(list(frame.getdata())) # Run through the image again print('Second run') for frame in ImageSequence.Iterator(im): print(list(frame.getdata())) ``` Output ``` First run [100] [121] [142] [163] Second run [163] [121] [142] [163] ```
Sounds fair enough to me. I've created a PR for review.
2016-01-27T01:56:43Z
3.1