Skip to content

Commit

Permalink
Merge pull request #6623 from radarhere/imt
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Oct 12, 2022
2 parents 5852b84 + cb22437 commit baaf654
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 9 deletions.
Binary file added Tests/images/bw_gradient.imt
Binary file not shown.
19 changes: 19 additions & 0 deletions Tests/test_file_imt.py
@@ -0,0 +1,19 @@
import io

import pytest

from PIL import Image, ImtImagePlugin

from .helper import assert_image_equal_tofile


def test_sanity():
with Image.open("Tests/images/bw_gradient.imt") as im:
assert_image_equal_tofile(im, "Tests/images/bw_gradient.png")


@pytest.mark.parametrize("data", (b"\n", b"\n-", b"width 1\n"))
def test_invalid_file(data):
with io.BytesIO(data) as fp:
with pytest.raises(SyntaxError):
ImtImagePlugin.ImtImageFile(fp)
30 changes: 21 additions & 9 deletions src/PIL/ImtImagePlugin.py
Expand Up @@ -39,32 +39,44 @@ def _open(self):
# Quick rejection: if there's not a LF among the first
# 100 bytes, this is (probably) not a text header.

if b"\n" not in self.fp.read(100):
buffer = self.fp.read(100)
if b"\n" not in buffer:
raise SyntaxError("not an IM file")
self.fp.seek(0)

xsize = ysize = 0

while True:

s = self.fp.read(1)
if buffer:
s = buffer[:1]
buffer = buffer[1:]
else:
s = self.fp.read(1)
if not s:
break

if s == b"\x0C":

# image data begins
self.tile = [
("raw", (0, 0) + self.size, self.fp.tell(), (self.mode, 0, 1))
(
"raw",
(0, 0) + self.size,
self.fp.tell() - len(buffer),
(self.mode, 0, 1),
)
]

break

else:

# read key/value pair
# FIXME: dangerous, may read whole file
s = s + self.fp.readline()
if b"\n" not in buffer:
buffer += self.fp.read(100)
lines = buffer.split(b"\n")
s += lines.pop(0)
buffer = b"\n".join(lines)
if len(s) == 1 or len(s) > 100:
break
if s[0] == ord(b"*"):
Expand All @@ -74,13 +86,13 @@ def _open(self):
if not m:
break
k, v = m.group(1, 2)
if k == "width":
if k == b"width":
xsize = int(v)
self._size = xsize, ysize
elif k == "height":
elif k == b"height":
ysize = int(v)
self._size = xsize, ysize
elif k == "pixel" and v == "n8":
elif k == b"pixel" and v == b"n8":
self.mode = "L"


Expand Down

0 comments on commit baaf654

Please sign in to comment.