IcoImagePlugin.py 12 KB

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