GribStubImagePlugin.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # GRIB stub adapter
  6. #
  7. # Copyright (c) 1996-2003 by Fredrik Lundh
  8. #
  9. # See the README file for information on usage and redistribution.
  10. #
  11. from . import Image, ImageFile
  12. from ._binary import i8
  13. _handler = None
  14. def register_handler(handler):
  15. """
  16. Install application-specific GRIB image handler.
  17. :param handler: Handler object.
  18. """
  19. global _handler
  20. _handler = handler
  21. # --------------------------------------------------------------------
  22. # Image adapter
  23. def _accept(prefix):
  24. return prefix[0:4] == b"GRIB" and i8(prefix[7]) == 1
  25. class GribStubImageFile(ImageFile.StubImageFile):
  26. format = "GRIB"
  27. format_description = "GRIB"
  28. def _open(self):
  29. offset = self.fp.tell()
  30. if not _accept(self.fp.read(8)):
  31. raise SyntaxError("Not a GRIB file")
  32. self.fp.seek(offset)
  33. # make something up
  34. self.mode = "F"
  35. self._size = 1, 1
  36. loader = self._load()
  37. if loader:
  38. loader.open(self)
  39. def _load(self):
  40. return _handler
  41. def _save(im, fp, filename):
  42. if _handler is None or not hasattr("_handler", "save"):
  43. raise IOError("GRIB save handler not installed")
  44. _handler.save(im, fp, filename)
  45. # --------------------------------------------------------------------
  46. # Registry
  47. Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
  48. Image.register_save(GribStubImageFile.format, _save)
  49. Image.register_extension(GribStubImageFile.format, ".grib")