We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
.ico files are saved as 255x255
### What did you do?

Loading an .ico of the size 256x256 and then saving it results in an .ico file of the size 255x255. I tested it on an example .ico file: http://www.axialis.com/tutorials/iw/down.ico

### What did you expect to happen?

The icon file should stay the same after saving. No other adjustments have been made. See the code below.

### What actually happened?

The saved .ico file ended up as 255x255 file. Because Windows doesn't support 255x255 size for .ico files, it is downscaled to 128x128 when used as desktop icons. [Example](http://i.imgur.com/fm7FTfw.png). The Chromium and Chrome icons are default ones, the Chrome Canary one was saved with Pillow.

### What versions of Pillow and Python are you using?
Pillow 3.4.2, Python 3.5.2

```python
from PIL import Image
im = Image.open('down.ico')
im.save('saved.ico')
im_saved = Image.open('saved.ico')

In [2]: im.size
Out[2]: (256, 256)

In [3]: im_saved.size
Out[3]: (255, 255)
```

`(255, 255)` appears on the list of sizes at https://github.com/python-pillow/Pillow/blob/master/PIL/IcoImagePlugin.py#L45 .

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `PIL/IcoImagePlugin.py`
Content:
```
1 #
2 # The Python Imaging Library.
3 # $Id$
4 #
5 # Windows Icon support for PIL
6 #
7 # History:
8 #       96-05-27 fl     Created
9 #
10 # Copyright (c) Secret Labs AB 1997.
11 # Copyright (c) Fredrik Lundh 1996.
12 #
13 # See the README file for information on usage and redistribution.
14 #
15 
16 # This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
17 # <casadebender@gmail.com>.
18 # https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
19 #
20 # Icon format references:
21 #   * https://en.wikipedia.org/wiki/ICO_(file_format)
22 #   * https://msdn.microsoft.com/en-us/library/ms997538.aspx
23 
24 
25 import struct
26 from io import BytesIO
27 
28 from PIL import Image, ImageFile, BmpImagePlugin, PngImagePlugin, _binary
29 from math import log, ceil
30 
31 __version__ = "0.1"
32 
33 #
34 # --------------------------------------------------------------------
35 
36 i8 = _binary.i8
37 i16 = _binary.i16le
38 i32 = _binary.i32le
39 
40 _MAGIC = b"\0\0\1\0"
41 
42 
43 def _save(im, fp, filename):
44     fp.write(_MAGIC)  # (2+2)
45     sizes = im.encoderinfo.get("sizes",
46                                [(16, 16), (24, 24), (32, 32), (48, 48),
47                                 (64, 64), (128, 128), (255, 255)])
48     width, height = im.size
49     filter(lambda x: False if (x[0] > width or x[1] > height or
50                                x[0] > 255 or x[1] > 255) else True, sizes)
51     fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
52     offset = fp.tell() + len(sizes)*16
53     for size in sizes:
54         width, height = size
55         fp.write(struct.pack("B", width))  # bWidth(1)
56         fp.write(struct.pack("B", height))  # bHeight(1)
57         fp.write(b"\0")  # bColorCount(1)
58         fp.write(b"\0")  # bReserved(1)
59         fp.write(b"\0\0")  # wPlanes(2)
60         fp.write(struct.pack("<H", 32))  # wBitCount(2)
61 
62         image_io = BytesIO()
63         tmp = im.copy()
64         tmp.thumbnail(size, Image.LANCZOS)
65         tmp.save(image_io, "png")
66         image_io.seek(0)
67         image_bytes = image_io.read()
68         bytes_len = len(image_bytes)
69         fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
70         fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
71         current = fp.tell()
72         fp.seek(offset)
73         fp.write(image_bytes)
74         offset = offset + bytes_len
75         fp.seek(current)
76 
77 
78 def _accept(prefix):
79     return prefix[:4] == _MAGIC
80 
81 
82 class IcoFile(object):
83     def __init__(self, buf):
84         """
85         Parse image from file-like object containing ico file data
86         """
87 
88         # check magic
89         s = buf.read(6)
90         if not _accept(s):
91             raise SyntaxError("not an ICO file")
92 
93         self.buf = buf
94         self.entry = []
95 
96         # Number of items in file
97         self.nb_items = i16(s[4:])
98 
99         # Get headers for each item
100         for i in range(self.nb_items):
101             s = buf.read(16)
102 
103             icon_header = {
104                 'width': i8(s[0]),
105                 'height': i8(s[1]),
106                 'nb_color': i8(s[2]),  # No. of colors in image (0 if >=8bpp)
107                 'reserved': i8(s[3]),
108                 'planes': i16(s[4:]),
109                 'bpp': i16(s[6:]),
110                 'size': i32(s[8:]),
111                 'offset': i32(s[12:])
112             }
113 
114             # See Wikipedia
115             for j in ('width', 'height'):
116                 if not icon_header[j]:
117                     icon_header[j] = 256
118 
119             # See Wikipedia notes about color depth.
120             # We need this just to differ images with equal sizes
121             icon_header['color_depth'] = (icon_header['bpp'] or
122                                           (icon_header['nb_color'] != 0 and
123                                            ceil(log(icon_header['nb_color'],
124                                                     2))) or 256)
125 
126             icon_header['dim'] = (icon_header['width'], icon_header['height'])
127             icon_header['square'] = (icon_header['width'] *
128                                      icon_header['height'])
129 
130             self.entry.append(icon_header)
131 
132         self.entry = sorted(self.entry, key=lambda x: x['color_depth'])
133         # ICO images are usually squares
134         # self.entry = sorted(self.entry, key=lambda x: x['width'])
135         self.entry = sorted(self.entry, key=lambda x: x['square'])
136         self.entry.reverse()
137 
138     def sizes(self):
139         """
140         Get a list of all available icon sizes and color depths.
141         """
142         return {(h['width'], h['height']) for h in self.entry}
143 
144     def getimage(self, size, bpp=False):
145         """
146         Get an image from the icon
147         """
148         for (i, h) in enumerate(self.entry):
149             if size == h['dim'] and (bpp is False or bpp == h['color_depth']):
150                 return self.frame(i)
151         return self.frame(0)
152 
153     def frame(self, idx):
154         """
155         Get an image from frame idx
156         """
157 
158         header = self.entry[idx]
159 
160         self.buf.seek(header['offset'])
161         data = self.buf.read(8)
162         self.buf.seek(header['offset'])
163 
164         if data[:8] == PngImagePlugin._MAGIC:
165             # png frame
166             im = PngImagePlugin.PngImageFile(self.buf)
167         else:
168             # XOR + AND mask bmp frame
169             im = BmpImagePlugin.DibImageFile(self.buf)
170 
171             # change tile dimension to only encompass XOR image
172             im.size = (im.size[0], int(im.size[1] / 2))
173             d, e, o, a = im.tile[0]
174             im.tile[0] = d, (0, 0) + im.size, o, a
175 
176             # figure out where AND mask image starts
177             mode = a[0]
178             bpp = 8
179             for k in BmpImagePlugin.BIT2MODE.keys():
180                 if mode == BmpImagePlugin.BIT2MODE[k][1]:
181                     bpp = k
182                     break
183 
184             if 32 == bpp:
185                 # 32-bit color depth icon image allows semitransparent areas
186                 # PIL's DIB format ignores transparency bits, recover them.
187                 # The DIB is packed in BGRX byte order where X is the alpha
188                 # channel.
189 
190                 # Back up to start of bmp data
191                 self.buf.seek(o)
192                 # extract every 4th byte (eg. 3,7,11,15,...)
193                 alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
194 
195                 # convert to an 8bpp grayscale image
196                 mask = Image.frombuffer(
197                     'L',            # 8bpp
198                     im.size,        # (w, h)
199                     alpha_bytes,    # source chars
200                     'raw',          # raw decoder
201                     ('L', 0, -1)    # 8bpp inverted, unpadded, reversed
202                 )
203             else:
204                 # get AND image from end of bitmap
205                 w = im.size[0]
206                 if (w % 32) > 0:
207                     # bitmap row data is aligned to word boundaries
208                     w += 32 - (im.size[0] % 32)
209 
210                 # the total mask data is
211                 # padded row size * height / bits per char
212 
213                 and_mask_offset = o + int(im.size[0] * im.size[1] *
214                                           (bpp / 8.0))
215                 total_bytes = int((w * im.size[1]) / 8)
216 
217                 self.buf.seek(and_mask_offset)
218                 maskData = self.buf.read(total_bytes)
219 
220                 # convert raw data to image
221                 mask = Image.frombuffer(
222                     '1',            # 1 bpp
223                     im.size,        # (w, h)
224                     maskData,       # source chars
225                     'raw',          # raw decoder
226                     ('1;I', int(w/8), -1)  # 1bpp inverted, padded, reversed
227                 )
228 
229                 # now we have two images, im is XOR image and mask is AND image
230 
231             # apply mask image as alpha channel
232             im = im.convert('RGBA')
233             im.putalpha(mask)
234 
235         return im
236 
237 
238 ##
239 # Image plugin for Windows Icon files.
240 
241 class IcoImageFile(ImageFile.ImageFile):
242     """
243     PIL read-only image support for Microsoft Windows .ico files.
244 
245     By default the largest resolution image in the file will be loaded. This
246     can be changed by altering the 'size' attribute before calling 'load'.
247 
248     The info dictionary has a key 'sizes' that is a list of the sizes available
249     in the icon file.
250 
251     Handles classic, XP and Vista icon formats.
252 
253     This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
254     <casadebender@gmail.com>.
255     https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
256     """
257     format = "ICO"
258     format_description = "Windows Icon"
259 
260     def _open(self):
261         self.ico = IcoFile(self.fp)
262         self.info['sizes'] = self.ico.sizes()
263         self.size = self.ico.entry[0]['dim']
264         self.load()
265 
266     def load(self):
267         im = self.ico.getimage(self.size)
268         # if tile is PNG, it won't really be loaded yet
269         im.load()
270         self.im = im.im
271         self.mode = im.mode
272         self.size = im.size
273 
274     def load_seek(self):
275         # Flag the ImageFile.Parser so that it
276         # just does all the decode at the end.
277         pass
278 #
279 # --------------------------------------------------------------------
280 
281 Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
282 Image.register_save(IcoImageFile.format, _save)
283 Image.register_extension(IcoImageFile.format, ".ico")
284
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/PIL/IcoImagePlugin.py b/PIL/IcoImagePlugin.py
--- a/PIL/IcoImagePlugin.py
+++ b/PIL/IcoImagePlugin.py
@@ -44,16 +44,17 @@
     fp.write(_MAGIC)  # (2+2)
     sizes = im.encoderinfo.get("sizes",
                                [(16, 16), (24, 24), (32, 32), (48, 48),
-                                (64, 64), (128, 128), (255, 255)])
+                                (64, 64), (128, 128), (256, 256)])
     width, height = im.size
     filter(lambda x: False if (x[0] > width or x[1] > height or
-                               x[0] > 255 or x[1] > 255) else True, sizes)
+                               x[0] > 256 or x[1] > 256) else True, sizes)
     fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
     offset = fp.tell() + len(sizes)*16
     for size in sizes:
         width, height = size
-        fp.write(struct.pack("B", width))  # bWidth(1)
-        fp.write(struct.pack("B", height))  # bHeight(1)
+        # 0 means 256
+        fp.write(struct.pack("B", width if width < 256 else 0))  # bWidth(1)
+        fp.write(struct.pack("B", height if height < 256 else 0))  # bHeight(1)
         fp.write(b"\0")  # bColorCount(1)
         fp.write(b"\0")  # bReserved(1)
         fp.write(b"\0\0")  # wPlanes(2)
@@ -215,13 +216,13 @@
                 total_bytes = int((w * im.size[1]) / 8)
 
                 self.buf.seek(and_mask_offset)
-                maskData = self.buf.read(total_bytes)
+                mask_data = self.buf.read(total_bytes)
 
                 # convert raw data to image
                 mask = Image.frombuffer(
                     '1',            # 1 bpp
                     im.size,        # (w, h)
-                    maskData,       # source chars
+                    mask_data,      # source chars
                     'raw',          # raw decoder
                     ('1;I', int(w/8), -1)  # 1bpp inverted, padded, reversed
                 )
@@ -278,6 +279,7 @@
 #
 # --------------------------------------------------------------------
 
+
 Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
 Image.register_save(IcoImageFile.format, _save)
 Image.register_extension(IcoImageFile.format, ".ico")

{"golden_diff": "diff --git a/PIL/IcoImagePlugin.py b/PIL/IcoImagePlugin.py\n--- a/PIL/IcoImagePlugin.py\n+++ b/PIL/IcoImagePlugin.py\n@@ -44,16 +44,17 @@\n     fp.write(_MAGIC)  # (2+2)\n     sizes = im.encoderinfo.get(\"sizes\",\n                                [(16, 16), (24, 24), (32, 32), (48, 48),\n-                                (64, 64), (128, 128), (255, 255)])\n+                                (64, 64), (128, 128), (256, 256)])\n     width, height = im.size\n     filter(lambda x: False if (x[0] > width or x[1] > height or\n-                               x[0] > 255 or x[1] > 255) else True, sizes)\n+                               x[0] > 256 or x[1] > 256) else True, sizes)\n     fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)\n     offset = fp.tell() + len(sizes)*16\n     for size in sizes:\n         width, height = size\n-        fp.write(struct.pack(\"B\", width))  # bWidth(1)\n-        fp.write(struct.pack(\"B\", height))  # bHeight(1)\n+        # 0 means 256\n+        fp.write(struct.pack(\"B\", width if width < 256 else 0))  # bWidth(1)\n+        fp.write(struct.pack(\"B\", height if height < 256 else 0))  # bHeight(1)\n         fp.write(b\"\\0\")  # bColorCount(1)\n         fp.write(b\"\\0\")  # bReserved(1)\n         fp.write(b\"\\0\\0\")  # wPlanes(2)\n@@ -215,13 +216,13 @@\n                 total_bytes = int((w * im.size[1]) / 8)\n \n                 self.buf.seek(and_mask_offset)\n-                maskData = self.buf.read(total_bytes)\n+                mask_data = self.buf.read(total_bytes)\n \n                 # convert raw data to image\n                 mask = Image.frombuffer(\n                     '1',            # 1 bpp\n                     im.size,        # (w, h)\n-                    maskData,       # source chars\n+                    mask_data,      # source chars\n                     'raw',          # raw decoder\n                     ('1;I', int(w/8), -1)  # 1bpp inverted, padded, reversed\n                 )\n@@ -278,6 +279,7 @@\n #\n # --------------------------------------------------------------------\n \n+\n Image.register_open(IcoImageFile.format, IcoImageFile, _accept)\n Image.register_save(IcoImageFile.format, _save)\n Image.register_extension(IcoImageFile.format, \".ico\")\n", "issue": ".ico files are saved as 255x255\n### What did you do?\r\n\r\nLoading an .ico of the size 256x256 and then saving it results in an .ico file of the size 255x255. I tested it on an example .ico file: http://www.axialis.com/tutorials/iw/down.ico\r\n\r\n### What did you expect to happen?\r\n\r\nThe icon file should stay the same after saving. No other adjustments have been made. See the code below.\r\n\r\n### What actually happened?\r\n\r\nThe saved .ico file ended up as 255x255 file. Because Windows doesn't support 255x255 size for .ico files, it is downscaled to 128x128 when used as desktop icons. [Example](http://i.imgur.com/fm7FTfw.png). The Chromium and Chrome icons are default ones, the Chrome Canary one was saved with Pillow.\r\n\r\n### What versions of Pillow and Python are you using?\r\nPillow 3.4.2, Python 3.5.2\r\n\r\n```python\r\nfrom PIL import Image\r\nim = Image.open('down.ico')\r\nim.save('saved.ico')\r\nim_saved = Image.open('saved.ico')\r\n\r\nIn [2]: im.size\r\nOut[2]: (256, 256)\r\n\r\nIn [3]: im_saved.size\r\nOut[3]: (255, 255)\r\n```\r\n\r\n`(255, 255)` appears on the list of sizes at https://github.com/python-pillow/Pillow/blob/master/PIL/IcoImagePlugin.py#L45 .\n", "before_files": [{"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# Windows Icon support for PIL\n#\n# History:\n#       96-05-27 fl     Created\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\n\n# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n# <casadebender@gmail.com>.\n# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n#\n# Icon format references:\n#   * https://en.wikipedia.org/wiki/ICO_(file_format)\n#   * https://msdn.microsoft.com/en-us/library/ms997538.aspx\n\n\nimport struct\nfrom io import BytesIO\n\nfrom PIL import Image, ImageFile, BmpImagePlugin, PngImagePlugin, _binary\nfrom math import log, ceil\n\n__version__ = \"0.1\"\n\n#\n# --------------------------------------------------------------------\n\ni8 = _binary.i8\ni16 = _binary.i16le\ni32 = _binary.i32le\n\n_MAGIC = b\"\\0\\0\\1\\0\"\n\n\ndef _save(im, fp, filename):\n    fp.write(_MAGIC)  # (2+2)\n    sizes = im.encoderinfo.get(\"sizes\",\n                               [(16, 16), (24, 24), (32, 32), (48, 48),\n                                (64, 64), (128, 128), (255, 255)])\n    width, height = im.size\n    filter(lambda x: False if (x[0] > width or x[1] > height or\n                               x[0] > 255 or x[1] > 255) else True, sizes)\n    fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)\n    offset = fp.tell() + len(sizes)*16\n    for size in sizes:\n        width, height = size\n        fp.write(struct.pack(\"B\", width))  # bWidth(1)\n        fp.write(struct.pack(\"B\", height))  # bHeight(1)\n        fp.write(b\"\\0\")  # bColorCount(1)\n        fp.write(b\"\\0\")  # bReserved(1)\n        fp.write(b\"\\0\\0\")  # wPlanes(2)\n        fp.write(struct.pack(\"<H\", 32))  # wBitCount(2)\n\n        image_io = BytesIO()\n        tmp = im.copy()\n        tmp.thumbnail(size, Image.LANCZOS)\n        tmp.save(image_io, \"png\")\n        image_io.seek(0)\n        image_bytes = image_io.read()\n        bytes_len = len(image_bytes)\n        fp.write(struct.pack(\"<I\", bytes_len))  # dwBytesInRes(4)\n        fp.write(struct.pack(\"<I\", offset))  # dwImageOffset(4)\n        current = fp.tell()\n        fp.seek(offset)\n        fp.write(image_bytes)\n        offset = offset + bytes_len\n        fp.seek(current)\n\n\ndef _accept(prefix):\n    return prefix[:4] == _MAGIC\n\n\nclass IcoFile(object):\n    def __init__(self, buf):\n        \"\"\"\n        Parse image from file-like object containing ico file data\n        \"\"\"\n\n        # check magic\n        s = buf.read(6)\n        if not _accept(s):\n            raise SyntaxError(\"not an ICO file\")\n\n        self.buf = buf\n        self.entry = []\n\n        # Number of items in file\n        self.nb_items = i16(s[4:])\n\n        # Get headers for each item\n        for i in range(self.nb_items):\n            s = buf.read(16)\n\n            icon_header = {\n                'width': i8(s[0]),\n                'height': i8(s[1]),\n                'nb_color': i8(s[2]),  # No. of colors in image (0 if >=8bpp)\n                'reserved': i8(s[3]),\n                'planes': i16(s[4:]),\n                'bpp': i16(s[6:]),\n                'size': i32(s[8:]),\n                'offset': i32(s[12:])\n            }\n\n            # See Wikipedia\n            for j in ('width', 'height'):\n                if not icon_header[j]:\n                    icon_header[j] = 256\n\n            # See Wikipedia notes about color depth.\n            # We need this just to differ images with equal sizes\n            icon_header['color_depth'] = (icon_header['bpp'] or\n                                          (icon_header['nb_color'] != 0 and\n                                           ceil(log(icon_header['nb_color'],\n                                                    2))) or 256)\n\n            icon_header['dim'] = (icon_header['width'], icon_header['height'])\n            icon_header['square'] = (icon_header['width'] *\n                                     icon_header['height'])\n\n            self.entry.append(icon_header)\n\n        self.entry = sorted(self.entry, key=lambda x: x['color_depth'])\n        # ICO images are usually squares\n        # self.entry = sorted(self.entry, key=lambda x: x['width'])\n        self.entry = sorted(self.entry, key=lambda x: x['square'])\n        self.entry.reverse()\n\n    def sizes(self):\n        \"\"\"\n        Get a list of all available icon sizes and color depths.\n        \"\"\"\n        return {(h['width'], h['height']) for h in self.entry}\n\n    def getimage(self, size, bpp=False):\n        \"\"\"\n        Get an image from the icon\n        \"\"\"\n        for (i, h) in enumerate(self.entry):\n            if size == h['dim'] and (bpp is False or bpp == h['color_depth']):\n                return self.frame(i)\n        return self.frame(0)\n\n    def frame(self, idx):\n        \"\"\"\n        Get an image from frame idx\n        \"\"\"\n\n        header = self.entry[idx]\n\n        self.buf.seek(header['offset'])\n        data = self.buf.read(8)\n        self.buf.seek(header['offset'])\n\n        if data[:8] == PngImagePlugin._MAGIC:\n            # png frame\n            im = PngImagePlugin.PngImageFile(self.buf)\n        else:\n            # XOR + AND mask bmp frame\n            im = BmpImagePlugin.DibImageFile(self.buf)\n\n            # change tile dimension to only encompass XOR image\n            im.size = (im.size[0], int(im.size[1] / 2))\n            d, e, o, a = im.tile[0]\n            im.tile[0] = d, (0, 0) + im.size, o, a\n\n            # figure out where AND mask image starts\n            mode = a[0]\n            bpp = 8\n            for k in BmpImagePlugin.BIT2MODE.keys():\n                if mode == BmpImagePlugin.BIT2MODE[k][1]:\n                    bpp = k\n                    break\n\n            if 32 == bpp:\n                # 32-bit color depth icon image allows semitransparent areas\n                # PIL's DIB format ignores transparency bits, recover them.\n                # The DIB is packed in BGRX byte order where X is the alpha\n                # channel.\n\n                # Back up to start of bmp data\n                self.buf.seek(o)\n                # extract every 4th byte (eg. 3,7,11,15,...)\n                alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]\n\n                # convert to an 8bpp grayscale image\n                mask = Image.frombuffer(\n                    'L',            # 8bpp\n                    im.size,        # (w, h)\n                    alpha_bytes,    # source chars\n                    'raw',          # raw decoder\n                    ('L', 0, -1)    # 8bpp inverted, unpadded, reversed\n                )\n            else:\n                # get AND image from end of bitmap\n                w = im.size[0]\n                if (w % 32) > 0:\n                    # bitmap row data is aligned to word boundaries\n                    w += 32 - (im.size[0] % 32)\n\n                # the total mask data is\n                # padded row size * height / bits per char\n\n                and_mask_offset = o + int(im.size[0] * im.size[1] *\n                                          (bpp / 8.0))\n                total_bytes = int((w * im.size[1]) / 8)\n\n                self.buf.seek(and_mask_offset)\n                maskData = self.buf.read(total_bytes)\n\n                # convert raw data to image\n                mask = Image.frombuffer(\n                    '1',            # 1 bpp\n                    im.size,        # (w, h)\n                    maskData,       # source chars\n                    'raw',          # raw decoder\n                    ('1;I', int(w/8), -1)  # 1bpp inverted, padded, reversed\n                )\n\n                # now we have two images, im is XOR image and mask is AND image\n\n            # apply mask image as alpha channel\n            im = im.convert('RGBA')\n            im.putalpha(mask)\n\n        return im\n\n\n##\n# Image plugin for Windows Icon files.\n\nclass IcoImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL read-only image support for Microsoft Windows .ico files.\n\n    By default the largest resolution image in the file will be loaded. This\n    can be changed by altering the 'size' attribute before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list of the sizes available\n    in the icon file.\n\n    Handles classic, XP and Vista icon formats.\n\n    This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n    <casadebender@gmail.com>.\n    https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n    \"\"\"\n    format = \"ICO\"\n    format_description = \"Windows Icon\"\n\n    def _open(self):\n        self.ico = IcoFile(self.fp)\n        self.info['sizes'] = self.ico.sizes()\n        self.size = self.ico.entry[0]['dim']\n        self.load()\n\n    def load(self):\n        im = self.ico.getimage(self.size)\n        # if tile is PNG, it won't really be loaded yet\n        im.load()\n        self.im = im.im\n        self.mode = im.mode\n        self.size = im.size\n\n    def load_seek(self):\n        # Flag the ImageFile.Parser so that it\n        # just does all the decode at the end.\n        pass\n#\n# --------------------------------------------------------------------\n\nImage.register_open(IcoImageFile.format, IcoImageFile, _accept)\nImage.register_save(IcoImageFile.format, _save)\nImage.register_extension(IcoImageFile.format, \".ico\")\n", "path": "PIL/IcoImagePlugin.py"}], "after_files": [{"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# Windows Icon support for PIL\n#\n# History:\n#       96-05-27 fl     Created\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\n\n# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n# <casadebender@gmail.com>.\n# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n#\n# Icon format references:\n#   * https://en.wikipedia.org/wiki/ICO_(file_format)\n#   * https://msdn.microsoft.com/en-us/library/ms997538.aspx\n\n\nimport struct\nfrom io import BytesIO\n\nfrom PIL import Image, ImageFile, BmpImagePlugin, PngImagePlugin, _binary\nfrom math import log, ceil\n\n__version__ = \"0.1\"\n\n#\n# --------------------------------------------------------------------\n\ni8 = _binary.i8\ni16 = _binary.i16le\ni32 = _binary.i32le\n\n_MAGIC = b\"\\0\\0\\1\\0\"\n\n\ndef _save(im, fp, filename):\n    fp.write(_MAGIC)  # (2+2)\n    sizes = im.encoderinfo.get(\"sizes\",\n                               [(16, 16), (24, 24), (32, 32), (48, 48),\n                                (64, 64), (128, 128), (256, 256)])\n    width, height = im.size\n    filter(lambda x: False if (x[0] > width or x[1] > height or\n                               x[0] > 256 or x[1] > 256) else True, sizes)\n    fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)\n    offset = fp.tell() + len(sizes)*16\n    for size in sizes:\n        width, height = size\n        # 0 means 256\n        fp.write(struct.pack(\"B\", width if width < 256 else 0))  # bWidth(1)\n        fp.write(struct.pack(\"B\", height if height < 256 else 0))  # bHeight(1)\n        fp.write(b\"\\0\")  # bColorCount(1)\n        fp.write(b\"\\0\")  # bReserved(1)\n        fp.write(b\"\\0\\0\")  # wPlanes(2)\n        fp.write(struct.pack(\"<H\", 32))  # wBitCount(2)\n\n        image_io = BytesIO()\n        tmp = im.copy()\n        tmp.thumbnail(size, Image.LANCZOS)\n        tmp.save(image_io, \"png\")\n        image_io.seek(0)\n        image_bytes = image_io.read()\n        bytes_len = len(image_bytes)\n        fp.write(struct.pack(\"<I\", bytes_len))  # dwBytesInRes(4)\n        fp.write(struct.pack(\"<I\", offset))  # dwImageOffset(4)\n        current = fp.tell()\n        fp.seek(offset)\n        fp.write(image_bytes)\n        offset = offset + bytes_len\n        fp.seek(current)\n\n\ndef _accept(prefix):\n    return prefix[:4] == _MAGIC\n\n\nclass IcoFile(object):\n    def __init__(self, buf):\n        \"\"\"\n        Parse image from file-like object containing ico file data\n        \"\"\"\n\n        # check magic\n        s = buf.read(6)\n        if not _accept(s):\n            raise SyntaxError(\"not an ICO file\")\n\n        self.buf = buf\n        self.entry = []\n\n        # Number of items in file\n        self.nb_items = i16(s[4:])\n\n        # Get headers for each item\n        for i in range(self.nb_items):\n            s = buf.read(16)\n\n            icon_header = {\n                'width': i8(s[0]),\n                'height': i8(s[1]),\n                'nb_color': i8(s[2]),  # No. of colors in image (0 if >=8bpp)\n                'reserved': i8(s[3]),\n                'planes': i16(s[4:]),\n                'bpp': i16(s[6:]),\n                'size': i32(s[8:]),\n                'offset': i32(s[12:])\n            }\n\n            # See Wikipedia\n            for j in ('width', 'height'):\n                if not icon_header[j]:\n                    icon_header[j] = 256\n\n            # See Wikipedia notes about color depth.\n            # We need this just to differ images with equal sizes\n            icon_header['color_depth'] = (icon_header['bpp'] or\n                                          (icon_header['nb_color'] != 0 and\n                                           ceil(log(icon_header['nb_color'],\n                                                    2))) or 256)\n\n            icon_header['dim'] = (icon_header['width'], icon_header['height'])\n            icon_header['square'] = (icon_header['width'] *\n                                     icon_header['height'])\n\n            self.entry.append(icon_header)\n\n        self.entry = sorted(self.entry, key=lambda x: x['color_depth'])\n        # ICO images are usually squares\n        # self.entry = sorted(self.entry, key=lambda x: x['width'])\n        self.entry = sorted(self.entry, key=lambda x: x['square'])\n        self.entry.reverse()\n\n    def sizes(self):\n        \"\"\"\n        Get a list of all available icon sizes and color depths.\n        \"\"\"\n        return {(h['width'], h['height']) for h in self.entry}\n\n    def getimage(self, size, bpp=False):\n        \"\"\"\n        Get an image from the icon\n        \"\"\"\n        for (i, h) in enumerate(self.entry):\n            if size == h['dim'] and (bpp is False or bpp == h['color_depth']):\n                return self.frame(i)\n        return self.frame(0)\n\n    def frame(self, idx):\n        \"\"\"\n        Get an image from frame idx\n        \"\"\"\n\n        header = self.entry[idx]\n\n        self.buf.seek(header['offset'])\n        data = self.buf.read(8)\n        self.buf.seek(header['offset'])\n\n        if data[:8] == PngImagePlugin._MAGIC:\n            # png frame\n            im = PngImagePlugin.PngImageFile(self.buf)\n        else:\n            # XOR + AND mask bmp frame\n            im = BmpImagePlugin.DibImageFile(self.buf)\n\n            # change tile dimension to only encompass XOR image\n            im.size = (im.size[0], int(im.size[1] / 2))\n            d, e, o, a = im.tile[0]\n            im.tile[0] = d, (0, 0) + im.size, o, a\n\n            # figure out where AND mask image starts\n            mode = a[0]\n            bpp = 8\n            for k in BmpImagePlugin.BIT2MODE.keys():\n                if mode == BmpImagePlugin.BIT2MODE[k][1]:\n                    bpp = k\n                    break\n\n            if 32 == bpp:\n                # 32-bit color depth icon image allows semitransparent areas\n                # PIL's DIB format ignores transparency bits, recover them.\n                # The DIB is packed in BGRX byte order where X is the alpha\n                # channel.\n\n                # Back up to start of bmp data\n                self.buf.seek(o)\n                # extract every 4th byte (eg. 3,7,11,15,...)\n                alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]\n\n                # convert to an 8bpp grayscale image\n                mask = Image.frombuffer(\n                    'L',            # 8bpp\n                    im.size,        # (w, h)\n                    alpha_bytes,    # source chars\n                    'raw',          # raw decoder\n                    ('L', 0, -1)    # 8bpp inverted, unpadded, reversed\n                )\n            else:\n                # get AND image from end of bitmap\n                w = im.size[0]\n                if (w % 32) > 0:\n                    # bitmap row data is aligned to word boundaries\n                    w += 32 - (im.size[0] % 32)\n\n                # the total mask data is\n                # padded row size * height / bits per char\n\n                and_mask_offset = o + int(im.size[0] * im.size[1] *\n                                          (bpp / 8.0))\n                total_bytes = int((w * im.size[1]) / 8)\n\n                self.buf.seek(and_mask_offset)\n                mask_data = self.buf.read(total_bytes)\n\n                # convert raw data to image\n                mask = Image.frombuffer(\n                    '1',            # 1 bpp\n                    im.size,        # (w, h)\n                    mask_data,      # source chars\n                    'raw',          # raw decoder\n                    ('1;I', int(w/8), -1)  # 1bpp inverted, padded, reversed\n                )\n\n                # now we have two images, im is XOR image and mask is AND image\n\n            # apply mask image as alpha channel\n            im = im.convert('RGBA')\n            im.putalpha(mask)\n\n        return im\n\n\n##\n# Image plugin for Windows Icon files.\n\nclass IcoImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL read-only image support for Microsoft Windows .ico files.\n\n    By default the largest resolution image in the file will be loaded. This\n    can be changed by altering the 'size' attribute before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list of the sizes available\n    in the icon file.\n\n    Handles classic, XP and Vista icon formats.\n\n    This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n    <casadebender@gmail.com>.\n    https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n    \"\"\"\n    format = \"ICO\"\n    format_description = \"Windows Icon\"\n\n    def _open(self):\n        self.ico = IcoFile(self.fp)\n        self.info['sizes'] = self.ico.sizes()\n        self.size = self.ico.entry[0]['dim']\n        self.load()\n\n    def load(self):\n        im = self.ico.getimage(self.size)\n        # if tile is PNG, it won't really be loaded yet\n        im.load()\n        self.im = im.im\n        self.mode = im.mode\n        self.size = im.size\n\n    def load_seek(self):\n        # Flag the ImageFile.Parser so that it\n        # just does all the decode at the end.\n        pass\n#\n# --------------------------------------------------------------------\n\n\nImage.register_open(IcoImageFile.format, IcoImageFile, _accept)\nImage.register_save(IcoImageFile.format, _save)\nImage.register_extension(IcoImageFile.format, \".ico\")\n", "path": "PIL/IcoImagePlugin.py"}]}