@@ -805,6 +805,41 @@ def test_save_bytesio_encoder_error(self) -> None:
805805 tiffinfo = {TiffImagePlugin .PREDICTOR : 3 },
806806 )
807807
808+ def test_save_bytesio_seek_past_end (self , tmp_path : Path ) -> None :
809+ # When writing the directory, libtiff seeks past the end of the data
810+ # written so far, and then writes the tag values there. Check that the
811+ # in-memory write buffer grows to fit, and that the bytes that are
812+ # skipped over are zero, as they would be when writing to a file.
813+
814+ # 7 distinct bytes per row: PackBits emits 8 bytes per row, so the strip
815+ # plus the header are exactly 64 KiB, the initial size of the buffer
816+ im = Image .new ("L" , (7 , 8191 ))
817+ im .putdata ([(i * 37 ) & 0xFF for i in range (7 * 8191 )])
818+ kwargs : dict [str , Any ] = {
819+ "compression" : "packbits" ,
820+ "description" : "D" * 65535 ,
821+ }
822+
823+ outfile = tmp_path / "temp.tif"
824+ im .save (outfile , ** kwargs )
825+ buffer_io = io .BytesIO ()
826+ im .save (buffer_io , format = "tiff" , ** kwargs )
827+ assert buffer_io .getvalue () == outfile .read_bytes ()
828+
829+ # odd-length tag values, so that libtiff pads between them. Large enough
830+ # that the buffer has to be reallocated
831+ im = hopper ().resize ((300 , 300 ))
832+ kwargs = {
833+ "compression" : "tiff_lzw" ,
834+ "description" : "abcdef" ,
835+ "software" : "xyz0" ,
836+ "tiffinfo" : {315 : "artist" , 33432 : "copyright!" },
837+ }
838+ im .save (outfile , ** kwargs )
839+ buffer_io = io .BytesIO ()
840+ im .save (buffer_io , format = "tiff" , ** kwargs )
841+ assert buffer_io .getvalue () == outfile .read_bytes ()
842+
808843 def test_save_ycbcr (self , tmp_path : Path ) -> None :
809844 im = hopper ("YCbCr" )
810845 outfile = tmp_path / "temp.tif"
0 commit comments