IcoImagePlugin.py 11 KB

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