GdImageFile.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 not i16(s) in [65534, 65535]:
  41. raise SyntaxError("Not a valid GD 2.x .gd file")
  42. self.mode = "L" # FIXME: "P"
  43. self._size = i16(s, 2), i16(s, 4)
  44. true_color = s[6]
  45. true_color_offset = 2 if true_color else 0
  46. # transparency index
  47. tindex = i32(s, 7 + true_color_offset)
  48. if tindex < 256:
  49. self.info["transparency"] = tindex
  50. self.palette = ImagePalette.raw(
  51. "XBGR", s[7 + true_color_offset + 4 : 7 + true_color_offset + 4 + 256 * 4]
  52. )
  53. self.tile = [
  54. (
  55. "raw",
  56. (0, 0) + self.size,
  57. 7 + true_color_offset + 4 + 256 * 4,
  58. ("L", 0, 1),
  59. )
  60. ]
  61. def open(fp, mode="r"):
  62. """
  63. Load texture from a GD image file.
  64. :param fp: GD file name, or an opened file handle.
  65. :param mode: Optional mode. In this version, if the mode argument
  66. is given, it must be "r".
  67. :returns: An image instance.
  68. :raises OSError: If the image could not be read.
  69. """
  70. if mode != "r":
  71. raise ValueError("bad mode")
  72. try:
  73. return GdImageFile(fp)
  74. except SyntaxError as e:
  75. raise UnidentifiedImageError("cannot identify this image file") from e