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. # NOTE: This format cannot be automatically recognized, so the
  16. # class is not registered for use with Image.open(). To open a
  17. # gd file, use the GdImageFile.open() function instead.
  18. # THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
  19. # implementation is provided for convenience and demonstrational
  20. # purposes only.
  21. from . import ImageFile, ImagePalette
  22. from ._binary import i8, i16be as i16, i32be as i32
  23. # __version__ is deprecated and will be removed in a future version. Use
  24. # PIL.__version__ instead.
  25. __version__ = "0.1"
  26. ##
  27. # Image plugin for the GD uncompressed format. Note that this format
  28. # is not supported by the standard <b>Image.open</b> function. To use
  29. # this plugin, you have to import the <b>GdImageFile</b> module and
  30. # use the <b>GdImageFile.open</b> function.
  31. class GdImageFile(ImageFile.ImageFile):
  32. format = "GD"
  33. format_description = "GD uncompressed images"
  34. def _open(self):
  35. # Header
  36. s = self.fp.read(1037)
  37. if not i16(s[:2]) in [65534, 65535]:
  38. raise SyntaxError("Not a valid GD 2.x .gd file")
  39. self.mode = "L" # FIXME: "P"
  40. self._size = i16(s[2:4]), i16(s[4:6])
  41. trueColor = i8(s[6])
  42. trueColorOffset = 2 if trueColor else 0
  43. # transparency index
  44. tindex = i32(s[7 + trueColorOffset : 7 + trueColorOffset + 4])
  45. if tindex < 256:
  46. self.info["transparency"] = tindex
  47. self.palette = ImagePalette.raw(
  48. "XBGR", s[7 + trueColorOffset + 4 : 7 + trueColorOffset + 4 + 256 * 4]
  49. )
  50. self.tile = [
  51. ("raw", (0, 0) + self.size, 7 + trueColorOffset + 4 + 256 * 4, ("L", 0, 1))
  52. ]
  53. def open(fp, mode="r"):
  54. """
  55. Load texture from a GD image file.
  56. :param filename: GD file name, or an opened file handle.
  57. :param mode: Optional mode. In this version, if the mode argument
  58. is given, it must be "r".
  59. :returns: An image instance.
  60. :raises IOError: If the image could not be read.
  61. """
  62. if mode != "r":
  63. raise ValueError("bad mode")
  64. try:
  65. return GdImageFile(fp)
  66. except SyntaxError:
  67. raise IOError("cannot identify this image file")