GdImageFile.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # GD file handling
  6. #
  7. # History:
  8. # 1996-04-12 fl Created
  9. #
  10. # Copyright (c) 1997 by Secret Labs AB.
  11. # Copyright (c) 1996 by Fredrik Lundh.
  12. #
  13. # See the README file for information on usage and redistribution.
  14. #
  15. """
  16. .. note::
  17. This format cannot be automatically recognized, so the
  18. class is not registered for use with :py:func:`PIL.Image.open()`. To open a
  19. gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
  20. .. warning::
  21. THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
  22. implementation is provided for convenience and demonstrational
  23. purposes only.
  24. """
  25. from __future__ import annotations
  26. from . import ImageFile, ImagePalette, UnidentifiedImageError
  27. from ._binary import i16be as i16
  28. from ._binary import i32be as i32
  29. class GdImageFile(ImageFile.ImageFile):
  30. """
  31. Image plugin for the GD uncompressed format. Note that this format
  32. is not supported by the standard :py:func:`PIL.Image.open()` function. To use
  33. this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
  34. use the :py:func:`PIL.GdImageFile.open()` function.
  35. """
  36. format = "GD"
  37. format_description = "GD uncompressed images"
  38. def _open(self):
  39. # Header
  40. s = self.fp.read(1037)
  41. if i16(s) not in [65534, 65535]:
  42. msg = "Not a valid GD 2.x .gd file"
  43. raise SyntaxError(msg)
  44. self._mode = "L" # FIXME: "P"
  45. self._size = i16(s, 2), i16(s, 4)
  46. true_color = s[6]
  47. true_color_offset = 2 if true_color else 0
  48. # transparency index
  49. tindex = i32(s, 7 + true_color_offset)
  50. if tindex < 256:
  51. self.info["transparency"] = tindex
  52. self.palette = ImagePalette.raw(
  53. "XBGR", s[7 + true_color_offset + 4 : 7 + true_color_offset + 4 + 256 * 4]
  54. )
  55. self.tile = [
  56. (
  57. "raw",
  58. (0, 0) + self.size,
  59. 7 + true_color_offset + 4 + 256 * 4,
  60. ("L", 0, 1),
  61. )
  62. ]
  63. def open(fp, mode="r"):
  64. """
  65. Load texture from a GD image file.
  66. :param fp: GD file name, or an opened file handle.
  67. :param mode: Optional mode. In this version, if the mode argument
  68. is given, it must be "r".
  69. :returns: An image instance.
  70. :raises OSError: If the image could not be read.
  71. """
  72. if mode != "r":
  73. msg = "bad mode"
  74. raise ValueError(msg)
  75. try:
  76. return GdImageFile(fp)
  77. except SyntaxError as e:
  78. msg = "cannot identify this image file"
  79. raise UnidentifiedImageError(msg) from e