FitsStubImagePlugin.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # FITS stub adapter
  6. #
  7. # Copyright (c) 1998-2003 by Fredrik Lundh
  8. #
  9. # See the README file for information on usage and redistribution.
  10. #
  11. from . import Image, ImageFile
  12. _handler = None
  13. def register_handler(handler):
  14. """
  15. Install application-specific FITS image handler.
  16. :param handler: Handler object.
  17. """
  18. global _handler
  19. _handler = handler
  20. # --------------------------------------------------------------------
  21. # Image adapter
  22. def _accept(prefix):
  23. return prefix[:6] == b"SIMPLE"
  24. class FITSStubImageFile(ImageFile.StubImageFile):
  25. format = "FITS"
  26. format_description = "FITS"
  27. def _open(self):
  28. offset = self.fp.tell()
  29. headers = {}
  30. while True:
  31. header = self.fp.read(80)
  32. if not header:
  33. raise OSError("Truncated FITS file")
  34. keyword = header[:8].strip()
  35. if keyword == b"END":
  36. break
  37. value = header[8:].strip()
  38. if value.startswith(b"="):
  39. value = value[1:].strip()
  40. if not headers and (not _accept(keyword) or value != b"T"):
  41. raise SyntaxError("Not a FITS file")
  42. headers[keyword] = value
  43. naxis = int(headers[b"NAXIS"])
  44. if naxis == 0:
  45. raise ValueError("No image data")
  46. elif naxis == 1:
  47. self._size = 1, int(headers[b"NAXIS1"])
  48. else:
  49. self._size = int(headers[b"NAXIS1"]), int(headers[b"NAXIS2"])
  50. number_of_bits = int(headers[b"BITPIX"])
  51. if number_of_bits == 8:
  52. self.mode = "L"
  53. elif number_of_bits == 16:
  54. self.mode = "I"
  55. # rawmode = "I;16S"
  56. elif number_of_bits == 32:
  57. self.mode = "I"
  58. elif number_of_bits in (-32, -64):
  59. self.mode = "F"
  60. # rawmode = "F" if number_of_bits == -32 else "F;64F"
  61. self.fp.seek(offset)
  62. loader = self._load()
  63. if loader:
  64. loader.open(self)
  65. def _load(self):
  66. return _handler
  67. def _save(im, fp, filename):
  68. if _handler is None or not hasattr("_handler", "save"):
  69. raise OSError("FITS save handler not installed")
  70. _handler.save(im, fp, filename)
  71. # --------------------------------------------------------------------
  72. # Registry
  73. Image.register_open(FITSStubImageFile.format, FITSStubImageFile, _accept)
  74. Image.register_save(FITSStubImageFile.format, _save)
  75. Image.register_extensions(FITSStubImageFile.format, [".fit", ".fits"])