IcnsImagePlugin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # macOS icns file decoder, based on icns.py by Bob Ippolito.
  6. #
  7. # history:
  8. # 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
  9. # 2020-04-04 Allow saving on all operating systems.
  10. #
  11. # Copyright (c) 2004 by Bob Ippolito.
  12. # Copyright (c) 2004 by Secret Labs.
  13. # Copyright (c) 2004 by Fredrik Lundh.
  14. # Copyright (c) 2014 by Alastair Houghton.
  15. # Copyright (c) 2020 by Pan Jing.
  16. #
  17. # See the README file for information on usage and redistribution.
  18. #
  19. import io
  20. import os
  21. import struct
  22. import sys
  23. from PIL import Image, ImageFile, PngImagePlugin, features
  24. enable_jpeg2k = features.check_codec("jpg_2000")
  25. if enable_jpeg2k:
  26. from PIL import Jpeg2KImagePlugin
  27. MAGIC = b"icns"
  28. HEADERSIZE = 8
  29. def nextheader(fobj):
  30. return struct.unpack(">4sI", fobj.read(HEADERSIZE))
  31. def read_32t(fobj, start_length, size):
  32. # The 128x128 icon seems to have an extra header for some reason.
  33. (start, length) = start_length
  34. fobj.seek(start)
  35. sig = fobj.read(4)
  36. if sig != b"\x00\x00\x00\x00":
  37. raise SyntaxError("Unknown signature, expecting 0x00000000")
  38. return read_32(fobj, (start + 4, length - 4), size)
  39. def read_32(fobj, start_length, size):
  40. """
  41. Read a 32bit RGB icon resource. Seems to be either uncompressed or
  42. an RLE packbits-like scheme.
  43. """
  44. (start, length) = start_length
  45. fobj.seek(start)
  46. pixel_size = (size[0] * size[2], size[1] * size[2])
  47. sizesq = pixel_size[0] * pixel_size[1]
  48. if length == sizesq * 3:
  49. # uncompressed ("RGBRGBGB")
  50. indata = fobj.read(length)
  51. im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
  52. else:
  53. # decode image
  54. im = Image.new("RGB", pixel_size, None)
  55. for band_ix in range(3):
  56. data = []
  57. bytesleft = sizesq
  58. while bytesleft > 0:
  59. byte = fobj.read(1)
  60. if not byte:
  61. break
  62. byte = byte[0]
  63. if byte & 0x80:
  64. blocksize = byte - 125
  65. byte = fobj.read(1)
  66. for i in range(blocksize):
  67. data.append(byte)
  68. else:
  69. blocksize = byte + 1
  70. data.append(fobj.read(blocksize))
  71. bytesleft -= blocksize
  72. if bytesleft <= 0:
  73. break
  74. if bytesleft != 0:
  75. raise SyntaxError(f"Error reading channel [{repr(bytesleft)} left]")
  76. band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
  77. im.im.putband(band.im, band_ix)
  78. return {"RGB": im}
  79. def read_mk(fobj, start_length, size):
  80. # Alpha masks seem to be uncompressed
  81. start = start_length[0]
  82. fobj.seek(start)
  83. pixel_size = (size[0] * size[2], size[1] * size[2])
  84. sizesq = pixel_size[0] * pixel_size[1]
  85. band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
  86. return {"A": band}
  87. def read_png_or_jpeg2000(fobj, start_length, size):
  88. (start, length) = start_length
  89. fobj.seek(start)
  90. sig = fobj.read(12)
  91. if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
  92. fobj.seek(start)
  93. im = PngImagePlugin.PngImageFile(fobj)
  94. Image._decompression_bomb_check(im.size)
  95. return {"RGBA": im}
  96. elif (
  97. sig[:4] == b"\xff\x4f\xff\x51"
  98. or sig[:4] == b"\x0d\x0a\x87\x0a"
  99. or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
  100. ):
  101. if not enable_jpeg2k:
  102. raise ValueError(
  103. "Unsupported icon subimage format (rebuild PIL "
  104. "with JPEG 2000 support to fix this)"
  105. )
  106. # j2k, jpc or j2c
  107. fobj.seek(start)
  108. jp2kstream = fobj.read(length)
  109. f = io.BytesIO(jp2kstream)
  110. im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
  111. Image._decompression_bomb_check(im.size)
  112. if im.mode != "RGBA":
  113. im = im.convert("RGBA")
  114. return {"RGBA": im}
  115. else:
  116. raise ValueError("Unsupported icon subimage format")
  117. class IcnsFile:
  118. SIZES = {
  119. (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
  120. (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
  121. (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
  122. (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
  123. (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
  124. (128, 128, 1): [
  125. (b"ic07", read_png_or_jpeg2000),
  126. (b"it32", read_32t),
  127. (b"t8mk", read_mk),
  128. ],
  129. (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
  130. (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
  131. (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
  132. (32, 32, 1): [
  133. (b"icp5", read_png_or_jpeg2000),
  134. (b"il32", read_32),
  135. (b"l8mk", read_mk),
  136. ],
  137. (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
  138. (16, 16, 1): [
  139. (b"icp4", read_png_or_jpeg2000),
  140. (b"is32", read_32),
  141. (b"s8mk", read_mk),
  142. ],
  143. }
  144. def __init__(self, fobj):
  145. """
  146. fobj is a file-like object as an icns resource
  147. """
  148. # signature : (start, length)
  149. self.dct = dct = {}
  150. self.fobj = fobj
  151. sig, filesize = nextheader(fobj)
  152. if sig != MAGIC:
  153. raise SyntaxError("not an icns file")
  154. i = HEADERSIZE
  155. while i < filesize:
  156. sig, blocksize = nextheader(fobj)
  157. if blocksize <= 0:
  158. raise SyntaxError("invalid block header")
  159. i += HEADERSIZE
  160. blocksize -= HEADERSIZE
  161. dct[sig] = (i, blocksize)
  162. fobj.seek(blocksize, io.SEEK_CUR)
  163. i += blocksize
  164. def itersizes(self):
  165. sizes = []
  166. for size, fmts in self.SIZES.items():
  167. for (fmt, reader) in fmts:
  168. if fmt in self.dct:
  169. sizes.append(size)
  170. break
  171. return sizes
  172. def bestsize(self):
  173. sizes = self.itersizes()
  174. if not sizes:
  175. raise SyntaxError("No 32bit icon resources found")
  176. return max(sizes)
  177. def dataforsize(self, size):
  178. """
  179. Get an icon resource as {channel: array}. Note that
  180. the arrays are bottom-up like windows bitmaps and will likely
  181. need to be flipped or transposed in some way.
  182. """
  183. dct = {}
  184. for code, reader in self.SIZES[size]:
  185. desc = self.dct.get(code)
  186. if desc is not None:
  187. dct.update(reader(self.fobj, desc, size))
  188. return dct
  189. def getimage(self, size=None):
  190. if size is None:
  191. size = self.bestsize()
  192. if len(size) == 2:
  193. size = (size[0], size[1], 1)
  194. channels = self.dataforsize(size)
  195. im = channels.get("RGBA", None)
  196. if im:
  197. return im
  198. im = channels.get("RGB").copy()
  199. try:
  200. im.putalpha(channels["A"])
  201. except KeyError:
  202. pass
  203. return im
  204. ##
  205. # Image plugin for Mac OS icons.
  206. class IcnsImageFile(ImageFile.ImageFile):
  207. """
  208. PIL image support for Mac OS .icns files.
  209. Chooses the best resolution, but will possibly load
  210. a different size image if you mutate the size attribute
  211. before calling 'load'.
  212. The info dictionary has a key 'sizes' that is a list
  213. of sizes that the icns file has.
  214. """
  215. format = "ICNS"
  216. format_description = "Mac OS icns resource"
  217. def _open(self):
  218. self.icns = IcnsFile(self.fp)
  219. self.mode = "RGBA"
  220. self.info["sizes"] = self.icns.itersizes()
  221. self.best_size = self.icns.bestsize()
  222. self.size = (
  223. self.best_size[0] * self.best_size[2],
  224. self.best_size[1] * self.best_size[2],
  225. )
  226. @property
  227. def size(self):
  228. return self._size
  229. @size.setter
  230. def size(self, value):
  231. info_size = value
  232. if info_size not in self.info["sizes"] and len(info_size) == 2:
  233. info_size = (info_size[0], info_size[1], 1)
  234. if (
  235. info_size not in self.info["sizes"]
  236. and len(info_size) == 3
  237. and info_size[2] == 1
  238. ):
  239. simple_sizes = [
  240. (size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
  241. ]
  242. if value in simple_sizes:
  243. info_size = self.info["sizes"][simple_sizes.index(value)]
  244. if info_size not in self.info["sizes"]:
  245. raise ValueError("This is not one of the allowed sizes of this image")
  246. self._size = value
  247. def load(self):
  248. if len(self.size) == 3:
  249. self.best_size = self.size
  250. self.size = (
  251. self.best_size[0] * self.best_size[2],
  252. self.best_size[1] * self.best_size[2],
  253. )
  254. Image.Image.load(self)
  255. if self.im and self.im.size == self.size:
  256. # Already loaded
  257. return
  258. self.load_prepare()
  259. # This is likely NOT the best way to do it, but whatever.
  260. im = self.icns.getimage(self.best_size)
  261. # If this is a PNG or JPEG 2000, it won't be loaded yet
  262. im.load()
  263. self.im = im.im
  264. self.mode = im.mode
  265. self.size = im.size
  266. self.load_end()
  267. def _save(im, fp, filename):
  268. """
  269. Saves the image as a series of PNG files,
  270. that are then combined into a .icns file.
  271. """
  272. if hasattr(fp, "flush"):
  273. fp.flush()
  274. sizes = {
  275. b"ic07": 128,
  276. b"ic08": 256,
  277. b"ic09": 512,
  278. b"ic10": 1024,
  279. b"ic11": 32,
  280. b"ic12": 64,
  281. b"ic13": 256,
  282. b"ic14": 512,
  283. }
  284. provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
  285. size_streams = {}
  286. for size in set(sizes.values()):
  287. image = (
  288. provided_images[size]
  289. if size in provided_images
  290. else im.resize((size, size))
  291. )
  292. temp = io.BytesIO()
  293. image.save(temp, "png")
  294. size_streams[size] = temp.getvalue()
  295. entries = []
  296. for type, size in sizes.items():
  297. stream = size_streams[size]
  298. entries.append({"type": type, "size": len(stream), "stream": stream})
  299. # Header
  300. fp.write(MAGIC)
  301. fp.write(struct.pack(">i", sum(entry["size"] for entry in entries)))
  302. # TOC
  303. fp.write(b"TOC ")
  304. fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
  305. for entry in entries:
  306. fp.write(entry["type"])
  307. fp.write(struct.pack(">i", HEADERSIZE + entry["size"]))
  308. # Data
  309. for entry in entries:
  310. fp.write(entry["type"])
  311. fp.write(struct.pack(">i", HEADERSIZE + entry["size"]))
  312. fp.write(entry["stream"])
  313. if hasattr(fp, "flush"):
  314. fp.flush()
  315. def _accept(prefix):
  316. return prefix[:4] == MAGIC
  317. Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
  318. Image.register_extension(IcnsImageFile.format, ".icns")
  319. Image.register_save(IcnsImageFile.format, _save)
  320. Image.register_mime(IcnsImageFile.format, "image/icns")
  321. if __name__ == "__main__":
  322. if len(sys.argv) < 2:
  323. print("Syntax: python3 IcnsImagePlugin.py [file]")
  324. sys.exit()
  325. with open(sys.argv[1], "rb") as fp:
  326. imf = IcnsImageFile(fp)
  327. for size in imf.info["sizes"]:
  328. imf.size = size
  329. imf.save("out-%s-%s-%s.png" % size)
  330. with Image.open(sys.argv[1]) as im:
  331. im.save("out.png")
  332. if sys.platform == "windows":
  333. os.startfile("out.png")