IcoImagePlugin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 warnings
  23. from io import BytesIO
  24. from math import ceil, log
  25. from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
  26. from ._binary import i16le as i16
  27. from ._binary import i32le as i32
  28. from ._binary import o8
  29. from ._binary import o16le as o16
  30. from ._binary import o32le as o32
  31. #
  32. # --------------------------------------------------------------------
  33. _MAGIC = b"\0\0\1\0"
  34. def _save(im, fp, filename):
  35. fp.write(_MAGIC) # (2+2)
  36. bmp = im.encoderinfo.get("bitmap_format") == "bmp"
  37. sizes = im.encoderinfo.get(
  38. "sizes",
  39. [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
  40. )
  41. frames = []
  42. provided_ims = [im] + im.encoderinfo.get("append_images", [])
  43. width, height = im.size
  44. for size in sorted(set(sizes)):
  45. if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256:
  46. continue
  47. for provided_im in provided_ims:
  48. if provided_im.size != size:
  49. continue
  50. frames.append(provided_im)
  51. if bmp:
  52. bits = BmpImagePlugin.SAVE[provided_im.mode][1]
  53. bits_used = [bits]
  54. for other_im in provided_ims:
  55. if other_im.size != size:
  56. continue
  57. bits = BmpImagePlugin.SAVE[other_im.mode][1]
  58. if bits not in bits_used:
  59. # Another image has been supplied for this size
  60. # with a different bit depth
  61. frames.append(other_im)
  62. bits_used.append(bits)
  63. break
  64. else:
  65. # TODO: invent a more convenient method for proportional scalings
  66. frame = provided_im.copy()
  67. frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None)
  68. frames.append(frame)
  69. fp.write(o16(len(frames))) # idCount(2)
  70. offset = fp.tell() + len(frames) * 16
  71. for frame in frames:
  72. width, height = frame.size
  73. # 0 means 256
  74. fp.write(o8(width if width < 256 else 0)) # bWidth(1)
  75. fp.write(o8(height if height < 256 else 0)) # bHeight(1)
  76. bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0)
  77. fp.write(o8(colors)) # bColorCount(1)
  78. fp.write(b"\0") # bReserved(1)
  79. fp.write(b"\0\0") # wPlanes(2)
  80. fp.write(o16(bits)) # wBitCount(2)
  81. image_io = BytesIO()
  82. if bmp:
  83. frame.save(image_io, "dib")
  84. if bits != 32:
  85. and_mask = Image.new("1", size)
  86. ImageFile._save(
  87. and_mask, image_io, [("raw", (0, 0) + size, 0, ("1", 0, -1))]
  88. )
  89. else:
  90. frame.save(image_io, "png")
  91. image_io.seek(0)
  92. image_bytes = image_io.read()
  93. if bmp:
  94. image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
  95. bytes_len = len(image_bytes)
  96. fp.write(o32(bytes_len)) # dwBytesInRes(4)
  97. fp.write(o32(offset)) # dwImageOffset(4)
  98. current = fp.tell()
  99. fp.seek(offset)
  100. fp.write(image_bytes)
  101. offset = offset + bytes_len
  102. fp.seek(current)
  103. def _accept(prefix):
  104. return prefix[:4] == _MAGIC
  105. class IcoFile:
  106. def __init__(self, buf):
  107. """
  108. Parse image from file-like object containing ico file data
  109. """
  110. # check magic
  111. s = buf.read(6)
  112. if not _accept(s):
  113. raise SyntaxError("not an ICO file")
  114. self.buf = buf
  115. self.entry = []
  116. # Number of items in file
  117. self.nb_items = i16(s, 4)
  118. # Get headers for each item
  119. for i in range(self.nb_items):
  120. s = buf.read(16)
  121. icon_header = {
  122. "width": s[0],
  123. "height": s[1],
  124. "nb_color": s[2], # No. of colors in image (0 if >=8bpp)
  125. "reserved": s[3],
  126. "planes": i16(s, 4),
  127. "bpp": i16(s, 6),
  128. "size": i32(s, 8),
  129. "offset": i32(s, 12),
  130. }
  131. # See Wikipedia
  132. for j in ("width", "height"):
  133. if not icon_header[j]:
  134. icon_header[j] = 256
  135. # See Wikipedia notes about color depth.
  136. # We need this just to differ images with equal sizes
  137. icon_header["color_depth"] = (
  138. icon_header["bpp"]
  139. or (
  140. icon_header["nb_color"] != 0
  141. and ceil(log(icon_header["nb_color"], 2))
  142. )
  143. or 256
  144. )
  145. icon_header["dim"] = (icon_header["width"], icon_header["height"])
  146. icon_header["square"] = icon_header["width"] * icon_header["height"]
  147. self.entry.append(icon_header)
  148. self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
  149. # ICO images are usually squares
  150. # self.entry = sorted(self.entry, key=lambda x: x['width'])
  151. self.entry = sorted(self.entry, key=lambda x: x["square"])
  152. self.entry.reverse()
  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. raise ValueError("This is not one of the allowed sizes of this image")
  263. self._size = value
  264. def load(self):
  265. if self.im is not None and self.im.size == self.size:
  266. # Already loaded
  267. return Image.Image.load(self)
  268. im = self.ico.getimage(self.size)
  269. # if tile is PNG, it won't really be loaded yet
  270. im.load()
  271. self.im = im.im
  272. self.mode = im.mode
  273. if im.size != self.size:
  274. warnings.warn("Image was not the expected size")
  275. index = self.ico.getentryindex(self.size)
  276. sizes = list(self.info["sizes"])
  277. sizes[index] = im.size
  278. self.info["sizes"] = set(sizes)
  279. self.size = im.size
  280. def load_seek(self):
  281. # Flag the ImageFile.Parser so that it
  282. # just does all the decode at the end.
  283. pass
  284. #
  285. # --------------------------------------------------------------------
  286. Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
  287. Image.register_save(IcoImageFile.format, _save)
  288. Image.register_extension(IcoImageFile.format, ".ico")
  289. Image.register_mime(IcoImageFile.format, "image/x-icon")