GdImageFile.py 2.4 KB

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