Skip to content

Commit 7752fb5

Browse files
kmilosradarhere
authored andcommitted
Limit TIFF strip size when saving with libtiff
1 parent 20bd9e9 commit 7752fb5

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/PIL/TiffImagePlugin.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1558,12 +1558,18 @@ def _save(im, fp, filename):
15581558
ifd[COLORMAP] = tuple(v * 256 for v in lut)
15591559
# data orientation
15601560
stride = len(bits) * ((im.size[0] * bits[0] + 7) // 8)
1561-
ifd[ROWSPERSTRIP] = im.size[1]
1561+
rows_per_strip = im.size[1]
15621562
strip_byte_counts = stride * im.size[1]
1563+
# aim for 64 KB strips when using libtiff writer
1564+
while libtiff and strip_byte_counts > 2 ** 16 and rows_per_strip > 1:
1565+
rows_per_strip = (rows_per_strip + 1) // 2
1566+
strip_byte_counts = stride * rows_per_strip
1567+
strips_per_image = (im.size[1] + rows_per_strip - 1) // rows_per_strip
1568+
ifd[ROWSPERSTRIP] = rows_per_strip
15631569
if strip_byte_counts >= 2 ** 16:
15641570
ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG
1565-
ifd[STRIPBYTECOUNTS] = strip_byte_counts
1566-
ifd[STRIPOFFSETS] = 0 # this is adjusted by IFD writer
1571+
ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + (stride * im.size[1] - strip_byte_counts * (strips_per_image - 1),)
1572+
ifd[STRIPOFFSETS] = tuple(range(0, strip_byte_counts * strips_per_image, strip_byte_counts)) # this is adjusted by IFD writer
15671573
# no compression by default:
15681574
ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)
15691575

0 commit comments

Comments
 (0)