GdImageFile.py 2.5 KB

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