diff --git a/PIL/XVThumbImagePlugin.py b/PIL/XVThumbImagePlugin.py index 6929e8b82..a7d39ed89 100644 --- a/PIL/XVThumbImagePlugin.py +++ b/PIL/XVThumbImagePlugin.py @@ -18,7 +18,7 @@ # from . import Image, ImageFile, ImagePalette -from ._binary import o8 +from ._binary import i8, o8 __version__ = "0.1" @@ -47,7 +47,7 @@ class XVThumbImageFile(ImageFile.ImageFile): def _open(self): # check magic - if self.fp.read(6) != _MAGIC: + if not _accept(self.fp.read(6)): raise SyntaxError("not an XV thumbnail file") # Skip to beginning of next line @@ -58,14 +58,14 @@ class XVThumbImageFile(ImageFile.ImageFile): s = self.fp.readline() if not s: raise SyntaxError("Unexpected EOF reading XV thumbnail file") - if s[0] != b'#': + if i8(s[0]) != 35: # ie. when not a comment: '#' break # parse header line (already read) s = s.strip().split() self.mode = "P" - self.size = int(s[0:1]), int(s[1:2]) + self.size = int(s[0]), int(s[1]) self.palette = ImagePalette.raw("RGB", PALETTE) @@ -74,6 +74,7 @@ class XVThumbImageFile(ImageFile.ImageFile): self.fp.tell(), (self.mode, 0, 1) )] + # -------------------------------------------------------------------- Image.register_open(XVThumbImageFile.format, XVThumbImageFile, _accept) diff --git a/Tests/images/hopper.p7 b/Tests/images/hopper.p7 new file mode 100644 index 000000000..474b233d5 Binary files /dev/null and b/Tests/images/hopper.p7 differ diff --git a/Tests/images/hopper_bad.p7 b/Tests/images/hopper_bad.p7 new file mode 100644 index 000000000..382929688 --- /dev/null +++ b/Tests/images/hopper_bad.p7 @@ -0,0 +1,2 @@ +P7 332 +# Artificially edited file to cause unexpected EOF diff --git a/Tests/test_file_xvthumb.py b/Tests/test_file_xvthumb.py index a4e1e6554..5337a8390 100644 --- a/Tests/test_file_xvthumb.py +++ b/Tests/test_file_xvthumb.py @@ -1,13 +1,38 @@ -from helper import unittest, PillowTestCase +from helper import hopper, unittest, PillowTestCase -from PIL import XVThumbImagePlugin +from PIL import Image, XVThumbImagePlugin + +TEST_FILE = "Tests/images/hopper.p7" class TestFileXVThumb(PillowTestCase): + def test_open(self): + # Act + im = Image.open(TEST_FILE) + + # Assert + self.assertEqual(im.format, "XVThumb") + + # Create a Hopper image with a similar XV palette + im_hopper = hopper().quantize(palette=im) + self.assert_image_similar(im, im_hopper, 9) + + def test_unexpected_eof(self): + # Test unexpected EOF reading XV thumbnail file + # Arrange + bad_file = "Tests/images/hopper_bad.p7" + + # Act / Assert + self.assertRaises(SyntaxError, + lambda: + XVThumbImagePlugin.XVThumbImageFile(bad_file)) + def test_invalid_file(self): + # Arrange invalid_file = "Tests/images/flower.jpg" + # Act / Assert self.assertRaises(SyntaxError, lambda: XVThumbImagePlugin.XVThumbImageFile(invalid_file))