XVThumbImagePlugin.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # XV Thumbnail file handler by Charles E. "Gene" Cash
  6. # (gcash@magicnet.net)
  7. #
  8. # see xvcolor.c and xvbrowse.c in the sources to John Bradley's XV,
  9. # available from ftp://ftp.cis.upenn.edu/pub/xv/
  10. #
  11. # history:
  12. # 98-08-15 cec created (b/w only)
  13. # 98-12-09 cec added color palette
  14. # 98-12-28 fl added to PIL (with only a few very minor modifications)
  15. #
  16. # To do:
  17. # FIXME: make save work (this requires quantization support)
  18. #
  19. from __future__ import annotations
  20. from . import Image, ImageFile, ImagePalette
  21. from ._binary import o8
  22. _MAGIC = b"P7 332"
  23. # standard color palette for thumbnails (RGB332)
  24. PALETTE = b""
  25. for r in range(8):
  26. for g in range(8):
  27. for b in range(4):
  28. PALETTE = PALETTE + (
  29. o8((r * 255) // 7) + o8((g * 255) // 7) + o8((b * 255) // 3)
  30. )
  31. def _accept(prefix: bytes) -> bool:
  32. return prefix[:6] == _MAGIC
  33. ##
  34. # Image plugin for XV thumbnail images.
  35. class XVThumbImageFile(ImageFile.ImageFile):
  36. format = "XVThumb"
  37. format_description = "XV thumbnail image"
  38. def _open(self) -> None:
  39. # check magic
  40. assert self.fp is not None
  41. if not _accept(self.fp.read(6)):
  42. msg = "not an XV thumbnail file"
  43. raise SyntaxError(msg)
  44. # Skip to beginning of next line
  45. self.fp.readline()
  46. # skip info comments
  47. while True:
  48. s = self.fp.readline()
  49. if not s:
  50. msg = "Unexpected EOF reading XV thumbnail file"
  51. raise SyntaxError(msg)
  52. if s[0] != 35: # ie. when not a comment: '#'
  53. break
  54. # parse header line (already read)
  55. s = s.strip().split()
  56. self._mode = "P"
  57. self._size = int(s[0]), int(s[1])
  58. self.palette = ImagePalette.raw("RGB", PALETTE)
  59. self.tile = [
  60. ImageFile._Tile("raw", (0, 0) + self.size, self.fp.tell(), self.mode)
  61. ]
  62. # --------------------------------------------------------------------
  63. Image.register_open(XVThumbImageFile.format, XVThumbImageFile, _accept)