IcoImagePlugin.py 9.9 KB

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