PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/resources/ico_tools.py

https://github.com/chromium/chromium
Python | 385 lines | 307 code | 23 blank | 55 comment | 22 complexity | 24c9c43785d0d27265042e3903f44341 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, Apache-2.0, BSD-3-Clause
  1. # Copyright 2015 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import logging
  5. import math
  6. import os
  7. import struct
  8. import subprocess
  9. import sys
  10. import tempfile
  11. OPTIMIZE_PNG_FILES = 'tools/resources/optimize-png-files.sh'
  12. IMAGEMAGICK_CONVERT = 'convert'
  13. logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
  14. class InvalidFile(Exception):
  15. """Represents an invalid ICO file."""
  16. def IsPng(png_data):
  17. """Determines whether a sequence of bytes is a PNG."""
  18. return png_data.startswith(b'\x89PNG\r\n\x1a\n')
  19. def OptimizePngFile(temp_dir, png_filename, optimization_level=None):
  20. """Optimize a PNG file.
  21. Args:
  22. temp_dir: The directory containing the PNG file. Must be the only file in
  23. the directory.
  24. png_filename: The full path to the PNG file to optimize.
  25. Returns:
  26. The raw bytes of a PNG file, an optimized version of the input.
  27. """
  28. logging.debug('Crushing PNG image...')
  29. args = [OPTIMIZE_PNG_FILES]
  30. if optimization_level is not None:
  31. args.append('-o%d' % optimization_level)
  32. args.append(temp_dir)
  33. result = subprocess.call(args, stdout=sys.stderr)
  34. if result != 0:
  35. logging.warning('Warning: optimize-png-files failed (%d)', result)
  36. else:
  37. logging.debug('optimize-png-files succeeded')
  38. with open(png_filename, 'rb') as png_file:
  39. return png_file.read()
  40. def OptimizePng(png_data, optimization_level=None):
  41. """Optimize a PNG.
  42. Args:
  43. png_data: The raw bytes of a PNG file.
  44. Returns:
  45. The raw bytes of a PNG file, an optimized version of the input.
  46. """
  47. temp_dir = tempfile.mkdtemp()
  48. try:
  49. logging.debug('temp_dir = %s', temp_dir)
  50. png_filename = os.path.join(temp_dir, 'image.png')
  51. with open(png_filename, 'wb') as png_file:
  52. png_file.write(png_data)
  53. return OptimizePngFile(temp_dir, png_filename,
  54. optimization_level=optimization_level)
  55. finally:
  56. if os.path.exists(png_filename):
  57. os.unlink(png_filename)
  58. os.rmdir(temp_dir)
  59. def BytesPerRowBMP(width, bpp):
  60. """Computes the number of bytes per row in a Windows BMP image."""
  61. # width * bpp / 8, rounded up to the nearest multiple of 4.
  62. return int(math.ceil(width * bpp / 32.0)) * 4
  63. def ExportSingleEntry(icon_dir_entry, icon_data, outfile):
  64. """Export a single icon dir entry to its own ICO file.
  65. Args:
  66. icon_dir_entry: Struct containing the fields of an ICONDIRENTRY.
  67. icon_data: Raw pixel data of the icon.
  68. outfile: File object to write to.
  69. """
  70. # Write the ICONDIR header.
  71. logging.debug('len(icon_data) = %d', len(icon_data))
  72. outfile.write(struct.pack('<HHH', 0, 1, 1))
  73. # Write the ICONDIRENTRY header.
  74. width, height, num_colors, r1, r2, r3, size, _ = icon_dir_entry
  75. offset = 22;
  76. icon_dir_entry = width, height, num_colors, r1, r2, r3, size, offset
  77. outfile.write(struct.pack('<BBBBHHLL', *icon_dir_entry))
  78. # Write the image data.
  79. outfile.write(icon_data)
  80. def ConvertIcoToPng(ico_filename, png_filename):
  81. """Convert a single-entry ICO file to a PNG image.
  82. Requires that the user has `convert` (ImageMagick) installed.
  83. Raises:
  84. OSError: If ImageMagick was not found.
  85. subprocess.CalledProcessError: If convert failed.
  86. """
  87. logging.debug('Converting BMP image to PNG...')
  88. args = [IMAGEMAGICK_CONVERT, ico_filename, png_filename]
  89. result = subprocess.check_call(args, stdout=sys.stderr)
  90. logging.info('Converted BMP image to PNG format')
  91. def OptimizeBmp(icon_dir_entry, icon_data):
  92. """Convert a BMP file to PNG and optimize it.
  93. Args:
  94. icon_dir_entry: Struct containing the fields of an ICONDIRENTRY.
  95. icon_data: Raw pixel data of the icon.
  96. Returns:
  97. The raw bytes of a PNG file, an optimized version of the input.
  98. """
  99. temp_dir = tempfile.mkdtemp()
  100. try:
  101. logging.debug('temp_dir = %s', temp_dir)
  102. ico_filename = os.path.join(temp_dir, 'image.ico')
  103. png_filename = os.path.join(temp_dir, 'image.png')
  104. with open(ico_filename, 'wb') as ico_file:
  105. logging.debug('writing %s', ico_filename)
  106. ExportSingleEntry(icon_dir_entry, icon_data, ico_file)
  107. try:
  108. ConvertIcoToPng(ico_filename, png_filename)
  109. except Exception as e:
  110. logging.warning('Could not convert BMP to PNG format: %s', e)
  111. if isinstance(e, OSError):
  112. logging.info('This is because ImageMagick (`convert`) was not found. '
  113. 'Please install it, or manually convert large BMP images '
  114. 'into PNG before running this utility.')
  115. return icon_data
  116. return OptimizePngFile(temp_dir, png_filename)
  117. finally:
  118. if os.path.exists(ico_filename):
  119. os.unlink(ico_filename)
  120. if os.path.exists(png_filename):
  121. os.unlink(png_filename)
  122. os.rmdir(temp_dir)
  123. def ComputeANDMaskFromAlpha(image_data, width, height):
  124. """Compute an AND mask from 32-bit BGRA image data."""
  125. and_bytes = []
  126. for y in range(height):
  127. bit_count = 0
  128. current_byte = 0
  129. for x in range(width):
  130. alpha = image_data[(y * width + x) * 4 + 3]
  131. current_byte <<= 1
  132. if alpha == 0:
  133. current_byte |= 1
  134. bit_count += 1
  135. if bit_count == 8:
  136. and_bytes.append(current_byte)
  137. bit_count = 0
  138. current_byte = 0
  139. # At the end of a row, pad the current byte.
  140. if bit_count > 0:
  141. current_byte <<= (8 - bit_count)
  142. and_bytes.append(current_byte)
  143. # And keep padding until a multiple of 4 bytes.
  144. while len(and_bytes) % 4 != 0:
  145. and_bytes.append(0)
  146. and_bytes = bytes(and_bytes)
  147. return and_bytes
  148. def CheckANDMaskAgainstAlpha(xor_data, and_data, width, height):
  149. """Checks whether an AND mask is "good" for 32-bit BGRA image data.
  150. This checks that the mask is opaque wherever the alpha channel is not fully
  151. transparent. Pixels that violate this condition will show up as black in some
  152. contexts in Windows (http://crbug.com/526622). Also checks the inverse
  153. condition, that the mask is transparent wherever the alpha channel is fully
  154. transparent. While this does not appear to be strictly necessary, it is good
  155. practice for backwards compatibility.
  156. Returns True if the AND mask is "good", False otherwise.
  157. """
  158. xor_bytes_per_row = width * 4
  159. and_bytes_per_row = BytesPerRowBMP(width, 1)
  160. for y in range(height):
  161. for x in range(width):
  162. alpha = xor_data[y * xor_bytes_per_row + x * 4 + 3]
  163. mask = bool(and_data[y * and_bytes_per_row + x // 8] & (1 << (7 -
  164. (x % 8))))
  165. if mask:
  166. if alpha > 0:
  167. # mask is transparent, alpha is partially or fully opaque. This pixel
  168. # can show up as black on Windows due to a rendering bug.
  169. return False
  170. else:
  171. if alpha == 0:
  172. # mask is opaque, alpha is transparent. This pixel should be marked as
  173. # transparent in the mask, for legacy reasons.
  174. return False
  175. return True
  176. def CheckOrRebuildANDMask(iconimage, rebuild=False):
  177. """Checks the AND mask in an icon image for correctness, or rebuilds it.
  178. GIMP (<=2.8.14) creates a bad AND mask on 32-bit icon images (pixels with <50%
  179. opacity are marked as transparent, which end up looking black on Windows).
  180. With rebuild == False, checks whether the mask is bad. With rebuild == True,
  181. if this is a 32-bit image, throw the mask away and recompute it from the alpha
  182. data. (See: https://bugzilla.gnome.org/show_bug.cgi?id=755200)
  183. Args:
  184. iconimage: Bytes of an icon image (the BMP data for an entry in an ICO
  185. file). Must be in BMP format, not PNG. Does not need to be 32-bit (if it
  186. is not 32-bit, this is a no-op).
  187. Returns:
  188. If rebuild == False, a bool indicating whether the mask is "good". If
  189. rebuild == True, an updated |iconimage|, with the AND mask re-computed using
  190. ComputeANDMaskFromAlpha.
  191. """
  192. # Parse BITMAPINFOHEADER.
  193. (_, width, height, _, bpp, _, _, _, _, num_colors, _) = struct.unpack(
  194. '<LLLHHLLLLLL', iconimage[:40])
  195. if bpp != 32:
  196. # No alpha channel, so the mask cannot be "wrong" (it is the only source of
  197. # transparency information).
  198. return iconimage if rebuild else True
  199. height = height // 2
  200. xor_size = BytesPerRowBMP(width, bpp) * height
  201. # num_colors can be 0, implying 2^bpp colors.
  202. xor_palette_size = (num_colors or (1 << bpp if bpp < 24 else 0)) * 4
  203. xor_data = iconimage[40 + xor_palette_size :
  204. 40 + xor_palette_size + xor_size]
  205. if rebuild:
  206. and_data = ComputeANDMaskFromAlpha(xor_data, width, height)
  207. # Replace the AND mask in the original icon data.
  208. return iconimage[:40 + xor_palette_size + xor_size] + and_data
  209. else:
  210. and_data = iconimage[40 + xor_palette_size + xor_size:]
  211. return CheckANDMaskAgainstAlpha(xor_data, and_data, width, height)
  212. def LintIcoFile(infile):
  213. """Read an ICO file and check whether it is acceptable.
  214. This checks for:
  215. - Basic structural integrity of the ICO.
  216. - Large BMPs that could be converted to PNGs.
  217. - 32-bit BMPs with buggy AND masks.
  218. It will *not* check whether PNG images have been compressed sufficiently.
  219. Args:
  220. infile: The file to read from. Must be a seekable file-like object
  221. containing a Microsoft ICO file.
  222. Returns:
  223. A sequence of strings, containing error messages. An empty sequence
  224. indicates a good icon.
  225. """
  226. filename = os.path.basename(infile.name)
  227. icondir = infile.read(6)
  228. zero, image_type, num_images = struct.unpack('<HHH', icondir)
  229. if zero != 0:
  230. yield 'Invalid ICO: First word must be 0.'
  231. return
  232. if image_type not in (1, 2):
  233. yield 'Invalid ICO: Image type must be 1 or 2.'
  234. return
  235. # Read and unpack each ICONDIRENTRY.
  236. icon_dir_entries = []
  237. for i in range(num_images):
  238. icondirentry = infile.read(16)
  239. icon_dir_entries.append(struct.unpack('<BBBBHHLL', icondirentry))
  240. # Read each icon's bitmap data.
  241. current_offset = infile.tell()
  242. icon_bitmap_data = []
  243. for i in range(num_images):
  244. width, height, num_colors, r1, r2, r3, size, _ = icon_dir_entries[i]
  245. width = width or 256
  246. height = height or 256
  247. offset = current_offset
  248. icon_data = infile.read(size)
  249. if len(icon_data) != size:
  250. yield 'Invalid ICO: Unexpected end of file'
  251. return
  252. entry_is_png = IsPng(icon_data)
  253. logging.debug('%s entry #%d: %dx%d, %d bytes (%s)', filename, i + 1, width,
  254. height, size, 'PNG' if entry_is_png else 'BMP')
  255. if not entry_is_png:
  256. if width >= 256 or height >= 256:
  257. yield ('Entry #%d is a large image in uncompressed BMP format. It '
  258. 'should be in PNG format.' % (i + 1))
  259. if not CheckOrRebuildANDMask(icon_data, rebuild=False):
  260. yield ('Entry #%d has a bad mask that will display incorrectly in some '
  261. 'places in Windows.' % (i + 1))
  262. def OptimizeIcoFile(infile, outfile, optimization_level=None):
  263. """Read an ICO file, optimize its PNGs, and write the output to outfile.
  264. Args:
  265. infile: The file to read from. Must be a seekable file-like object
  266. containing a Microsoft ICO file.
  267. outfile: The file to write to.
  268. """
  269. filename = os.path.basename(infile.name)
  270. icondir = infile.read(6)
  271. zero, image_type, num_images = struct.unpack('<HHH', icondir)
  272. if zero != 0:
  273. raise InvalidFile('First word must be 0.')
  274. if image_type not in (1, 2):
  275. raise InvalidFile('Image type must be 1 or 2.')
  276. # Read and unpack each ICONDIRENTRY.
  277. icon_dir_entries = []
  278. for i in range(num_images):
  279. icondirentry = infile.read(16)
  280. icon_dir_entries.append(struct.unpack('<BBBBHHLL', icondirentry))
  281. # Read each icon's bitmap data, crush PNGs, and update icon dir entries.
  282. current_offset = infile.tell()
  283. icon_bitmap_data = []
  284. for i in range(num_images):
  285. width, height, num_colors, r1, r2, r3, size, _ = icon_dir_entries[i]
  286. width = width or 256
  287. height = height or 256
  288. offset = current_offset
  289. icon_data = infile.read(size)
  290. if len(icon_data) != size:
  291. raise EOFError()
  292. entry_is_png = IsPng(icon_data)
  293. logging.info('%s entry #%d: %dx%d, %d bytes (%s)', filename, i + 1, width,
  294. height, size, 'PNG' if entry_is_png else 'BMP')
  295. if entry_is_png:
  296. # It is a PNG. Crush it.
  297. icon_data = OptimizePng(icon_data, optimization_level=optimization_level)
  298. elif width >= 256 or height >= 256:
  299. # It is a large BMP. Reformat as a PNG, then crush it.
  300. # Note: Smaller images are kept uncompressed, for compatibility with
  301. # Windows XP.
  302. # TODO(mgiuca): Now that we no longer support XP, we can probably compress
  303. # all of the images. https://crbug.com/663136
  304. icon_data = OptimizeBmp(icon_dir_entries[i], icon_data)
  305. else:
  306. new_icon_data = CheckOrRebuildANDMask(icon_data, rebuild=True)
  307. if new_icon_data != icon_data:
  308. logging.info(' * Rebuilt AND mask for this image from alpha channel.')
  309. icon_data = new_icon_data
  310. new_size = len(icon_data)
  311. current_offset += new_size
  312. icon_dir_entries[i] = (width % 256, height % 256, num_colors, r1, r2, r3,
  313. new_size, offset)
  314. icon_bitmap_data.append(icon_data)
  315. # Write the data back to outfile.
  316. outfile.write(icondir)
  317. for icon_dir_entry in icon_dir_entries:
  318. outfile.write(struct.pack('<BBBBHHLL', *icon_dir_entry))
  319. for icon_bitmap in icon_bitmap_data:
  320. outfile.write(icon_bitmap)