IcoImagePlugin.py 13 KB

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