Skip to content

Commit

Permalink
Finish reading data at eof
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed Mar 4, 2022
1 parent e383646 commit f78eb56
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
21 changes: 21 additions & 0 deletions Tests/test_file_bmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,27 @@ def test_rle8():
with Image.open("Tests/images/hopper_rle8_row_overflow.bmp") as im:
assert_image_similar_tofile(im.convert("RGB"), "Tests/images/hopper.bmp", 12)

# Test EOF immediately after the header
with open("Tests/images/hopper_rle8.bmp", "rb") as fp:
data = fp.read(1078)
with Image.open(io.BytesIO(data)) as im:
with pytest.raises(ValueError):
im.load()

# Test EOF during delta
with open("Tests/images/bmp/q/pal8rletrns.bmp", "rb") as fp:
data = fp.read(3670)
with Image.open(io.BytesIO(data)) as im:
with pytest.raises(ValueError):
im.load()

# Test EOF when reading data in absolute mode
with open("Tests/images/bmp/g/pal8rle.bmp", "rb") as fp:
data = fp.read(1064)
with Image.open(io.BytesIO(data)) as im:
with pytest.raises(ValueError):
im.load()


def test_offset():
# This image has been hexedited
Expand Down
13 changes: 11 additions & 2 deletions src/PIL/BmpImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,11 @@ def decode(self, buffer):
data = b""
x = 0
while len(data) < self.state.xsize * self.state.ysize:
num_pixels = self.fd.read(1)[0]
pixels = self.fd.read(1)
byte = self.fd.read(1)
if not pixels or not byte:
break
num_pixels = pixels[0]
if num_pixels:
# encoded mode
if x + num_pixels > self.state.xsize:
Expand All @@ -303,12 +306,18 @@ def decode(self, buffer):
break
elif byte[0] == 2:
# delta
bytes_read = self.fd.read(2)
if len(bytes_read) < 2:
break
right, up = self.fd.read(2)
data += b"\x00" * (right + up * self.state.xsize)
x = len(data) % self.state.xsize
else:
# absolute mode
data += self.fd.read(byte[0])
bytes_read = self.fd.read(byte[0])
data += bytes_read
if len(bytes_read) < byte[0]:
break
x += byte[0]

# align to 16-bit word boundary
Expand Down

0 comments on commit f78eb56

Please sign in to comment.