Raise an error if BMP file size is too large when saving

This commit is contained in:
Andrew Murray 2019-12-21 08:37:40 +11:00
parent ce62dca326
commit 4580b156b7
2 changed files with 11 additions and 1 deletions

View File

@ -41,6 +41,13 @@ class TestFileBmp(PillowTestCase):
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)

View File

@ -321,9 +321,12 @@ 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" # file type (magic)
+ o32(offset + image) # file size
+ o32(file_size) # file size
+ o32(0) # reserved
+ o32(offset) # image data offset
)