diff --git a/Tests/images/hopper_unexpected.ico b/Tests/images/hopper_unexpected.ico new file mode 100644 index 00000000000..639828ae045 Binary files /dev/null and b/Tests/images/hopper_unexpected.ico differ diff --git a/Tests/test_file_ico.py b/Tests/test_file_ico.py index f6244e0868d..97fb781b35d 100644 --- a/Tests/test_file_ico.py +++ b/Tests/test_file_ico.py @@ -83,3 +83,10 @@ def test_only_save_relevant_sizes(self): self.assertEqual( im_saved.info['sizes'], {(16, 16), (24, 24), (32, 32), (48, 48)}) + + def test_unexpected_size(self): + # This image has been manually hexedited to state that it is 16x32 + # while the image within is still 16x16 + im = self.assert_warning(UserWarning, + Image.open, "Tests/images/hopper_unexpected.ico") + self.assertEqual(im.size, (16, 16)) diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py index c1c0775daf9..d56335971ea 100644 --- a/src/PIL/IcoImagePlugin.py +++ b/src/PIL/IcoImagePlugin.py @@ -23,6 +23,7 @@ import struct +import warnings from io import BytesIO from . import Image, ImageFile, BmpImagePlugin, PngImagePlugin @@ -143,14 +144,17 @@ def sizes(self): """ return {(h['width'], h['height']) for h in self.entry} + def getentryindex(self, size, bpp=False): + for (i, h) in enumerate(self.entry): + if size == h['dim'] and (bpp is False or bpp == h['color_depth']): + return i + return 0 + def getimage(self, size, bpp=False): """ Get an image from the icon """ - for (i, h) in enumerate(self.entry): - if size == h['dim'] and (bpp is False or bpp == h['color_depth']): - return self.frame(i) - return self.frame(0) + return self.frame(self.getentryindex(size, bpp)) def frame(self, idx): """ @@ -282,7 +286,15 @@ def load(self): im.load() self.im = im.im self.mode = im.mode - self.size = im.size + if im.size != self.size: + warnings.warn("Image was not the expected size") + + index = self.ico.getentryindex(self.size) + sizes = list(self.info['sizes']) + sizes[index] = im.size + self.info['sizes'] = set(sizes) + + self.size = im.size def load_seek(self): # Flag the ImageFile.Parser so that it