icon.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2022-2023, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. from typing import Tuple
  12. import os
  13. import hashlib
  14. def normalize_icon_type(icon_path: str, allowed_types: Tuple[str], convert_type: str, workpath: str) -> str:
  15. """
  16. Returns a valid icon path or raises an Exception on error.
  17. Ensures that the icon exists, and, if necessary, attempts to convert it to correct OS-specific format using Pillow.
  18. Takes:
  19. icon_path - the icon given by the user
  20. allowed_types - a tuple of icon formats that should be allowed through
  21. EX: ("ico", "exe")
  22. convert_type - the type to attempt conversion too if necessary
  23. EX: "icns"
  24. workpath - the temp directory to save any newly generated image files
  25. """
  26. # explicitly error if file not found
  27. if not os.path.exists(icon_path):
  28. raise FileNotFoundError(f"Icon input file {icon_path} not found")
  29. _, extension = os.path.splitext(icon_path)
  30. extension = extension[1:] # get rid of the "." in ".whatever"
  31. # if the file is already in the right format, pass it back unchanged
  32. if extension in allowed_types:
  33. # Check both the suffix and the header of the file to guard against the user confusing image types.
  34. signatures = hex_signatures[extension]
  35. with open(icon_path, "rb") as f:
  36. header = f.read(max(len(s) for s in signatures))
  37. if any(list(header)[:len(s)] == s for s in signatures):
  38. return icon_path
  39. # The icon type is wrong! Let's try and import PIL
  40. try:
  41. from PIL import Image as PILImage
  42. import PIL
  43. except ImportError:
  44. raise ValueError(
  45. f"Received icon image '{icon_path}' which exists but is not in the correct format. On this platform, "
  46. f"only {allowed_types} images may be used as icons. If Pillow is installed, automatic conversion will "
  47. f"be attempted. Please install Pillow or convert your '{extension}' file to one of {allowed_types} "
  48. f"and try again."
  49. )
  50. # Let's try to use PIL to convert the icon file type
  51. try:
  52. _generated_name = f"generated-{hashlib.sha256(icon_path.encode()).hexdigest()}.{convert_type}"
  53. generated_icon = os.path.join(workpath, _generated_name)
  54. with PILImage.open(icon_path) as im:
  55. # If an image uses a custom palette + transparency, convert it to RGBA for a better alpha mask depth.
  56. if im.mode == "P" and im.info.get("transparency", None) is not None:
  57. # The bit depth of the alpha channel will be higher, and the images will look better when eventually
  58. # scaled to multiple sizes (16,24,32,..) for the ICO format for example.
  59. im = im.convert("RGBA")
  60. im.save(generated_icon)
  61. icon_path = generated_icon
  62. except PIL.UnidentifiedImageError:
  63. raise ValueError(
  64. f"Something went wrong converting icon image '{icon_path}' to '.{convert_type}' with Pillow, "
  65. f"perhaps the image format is unsupported. Try again with a different file or use a file that can "
  66. f"be used without conversion on this platform: {allowed_types}"
  67. )
  68. return icon_path
  69. # Possible initial bytes of icon types PyInstaller needs to be able to recognise.
  70. # Taken from: https://en.wikipedia.org/wiki/List_of_file_signatures
  71. hex_signatures = {
  72. "png": [[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]],
  73. "exe": [[0x4D, 0x5A], [0x5A, 0x4D]],
  74. "ico": [[0x00, 0x00, 0x01, 0x00]],
  75. "icns": [[0x69, 0x63, 0x6e, 0x73]],
  76. }