GdImageFile.py 2.5 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 . import ImageFile, ImagePalette, UnidentifiedImageError
  26. from ._binary import i16be as i16
  27. from ._binary import i32be as i32
  28. class GdImageFile(ImageFile.ImageFile):
  29. """
  30. Image plugin for the GD uncompressed format. Note that this format
  31. is not supported by the standard :py:func:`PIL.Image.open()` function. To use
  32. this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
  33. use the :py:func:`PIL.GdImageFile.open()` function.
  34. """
  35. format = "GD"
  36. format_description = "GD uncompressed images"
  37. def _open(self):
  38. # Header
  39. s = self.fp.read(1037)
  40. if i16(s) not in [65534, 65535]:
  41. msg = "Not a valid GD 2.x .gd file"
  42. raise SyntaxError(msg)
  43. self._mode = "L" # FIXME: "P"
  44. self._size = i16(s, 2), i16(s, 4)
  45. true_color = s[6]
  46. true_color_offset = 2 if true_color else 0
  47. # transparency index
  48. tindex = i32(s, 7 + true_color_offset)
  49. if tindex < 256:
  50. self.info["transparency"] = tindex
  51. self.palette = ImagePalette.raw(
  52. "XBGR", s[7 + true_color_offset + 4 : 7 + true_color_offset + 4 + 256 * 4]
  53. )
  54. self.tile = [
  55. (
  56. "raw",
  57. (0, 0) + self.size,
  58. 7 + true_color_offset + 4 + 256 * 4,
  59. ("L", 0, 1),
  60. )
  61. ]
  62. def open(fp, mode="r"):
  63. """
  64. Load texture from a GD image file.
  65. :param fp: GD file name, or an opened file handle.
  66. :param mode: Optional mode. In this version, if the mode argument
  67. is given, it must be "r".
  68. :returns: An image instance.
  69. :raises OSError: If the image could not be read.
  70. """
  71. if mode != "r":
  72. msg = "bad mode"
  73. raise ValueError(msg)
  74. try:
  75. return GdImageFile(fp)
  76. except SyntaxError as e:
  77. msg = "cannot identify this image file"
  78. raise UnidentifiedImageError(msg) from e