diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py index 907931b926e..24344e876eb 100644 --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -371,19 +371,20 @@ def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: x = len(data) % self.state.xsize else: # absolute mode + data_count = min(dest_length - len(data), byte[0]) if rle4: # 2 pixels per byte, padded up to a whole byte - byte_count = (byte[0] + 1) // 2 + byte_count = (data_count + 1) // 2 bytes_read = self.fd.read(byte_count) for i, byte_read in enumerate(bytes_read): data += o8(byte_read >> 4) - if 2 * i + 1 < byte[0]: + if i * 2 + 1 < data_count: data += o8(byte_read & 0x0F) else: - byte_count = byte[0] + byte_count = data_count bytes_read = self.fd.read(byte_count) data += bytes_read - if len(bytes_read) < byte_count: + if len(bytes_read) < byte_count or len(data) == dest_length: break x += byte[0]