PsdImagePlugin.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # Adobe PSD 2.5/3.0 file handling
  6. #
  7. # History:
  8. # 1995-09-01 fl Created
  9. # 1997-01-03 fl Read most PSD images
  10. # 1997-01-18 fl Fixed P and CMYK support
  11. # 2001-10-21 fl Added seek/tell support (for layers)
  12. #
  13. # Copyright (c) 1997-2001 by Secret Labs AB.
  14. # Copyright (c) 1995-2001 by Fredrik Lundh
  15. #
  16. # See the README file for information on usage and redistribution.
  17. #
  18. import io
  19. from . import Image, ImageFile, ImagePalette
  20. from ._binary import i8
  21. from ._binary import i16be as i16
  22. from ._binary import i32be as i32
  23. MODES = {
  24. # (photoshop mode, bits) -> (pil mode, required channels)
  25. (0, 1): ("1", 1),
  26. (0, 8): ("L", 1),
  27. (1, 8): ("L", 1),
  28. (2, 8): ("P", 1),
  29. (3, 8): ("RGB", 3),
  30. (4, 8): ("CMYK", 4),
  31. (7, 8): ("L", 1), # FIXME: multilayer
  32. (8, 8): ("L", 1), # duotone
  33. (9, 8): ("LAB", 3),
  34. }
  35. # --------------------------------------------------------------------.
  36. # read PSD images
  37. def _accept(prefix):
  38. return prefix[:4] == b"8BPS"
  39. ##
  40. # Image plugin for Photoshop images.
  41. class PsdImageFile(ImageFile.ImageFile):
  42. format = "PSD"
  43. format_description = "Adobe Photoshop"
  44. _close_exclusive_fp_after_loading = False
  45. def _open(self):
  46. read = self.fp.read
  47. #
  48. # header
  49. s = read(26)
  50. if not _accept(s) or i16(s, 4) != 1:
  51. raise SyntaxError("not a PSD file")
  52. psd_bits = i16(s, 22)
  53. psd_channels = i16(s, 12)
  54. psd_mode = i16(s, 24)
  55. mode, channels = MODES[(psd_mode, psd_bits)]
  56. if channels > psd_channels:
  57. raise OSError("not enough channels")
  58. self.mode = mode
  59. self._size = i32(s, 18), i32(s, 14)
  60. #
  61. # color mode data
  62. size = i32(read(4))
  63. if size:
  64. data = read(size)
  65. if mode == "P" and size == 768:
  66. self.palette = ImagePalette.raw("RGB;L", data)
  67. #
  68. # image resources
  69. self.resources = []
  70. size = i32(read(4))
  71. if size:
  72. # load resources
  73. end = self.fp.tell() + size
  74. while self.fp.tell() < end:
  75. read(4) # signature
  76. id = i16(read(2))
  77. name = read(i8(read(1)))
  78. if not (len(name) & 1):
  79. read(1) # padding
  80. data = read(i32(read(4)))
  81. if len(data) & 1:
  82. read(1) # padding
  83. self.resources.append((id, name, data))
  84. if id == 1039: # ICC profile
  85. self.info["icc_profile"] = data
  86. #
  87. # layer and mask information
  88. self.layers = []
  89. size = i32(read(4))
  90. if size:
  91. end = self.fp.tell() + size
  92. size = i32(read(4))
  93. if size:
  94. _layer_data = io.BytesIO(ImageFile._safe_read(self.fp, size))
  95. self.layers = _layerinfo(_layer_data, size)
  96. self.fp.seek(end)
  97. self.n_frames = len(self.layers)
  98. self.is_animated = self.n_frames > 1
  99. #
  100. # image descriptor
  101. self.tile = _maketile(self.fp, mode, (0, 0) + self.size, channels)
  102. # keep the file open
  103. self.__fp = self.fp
  104. self.frame = 1
  105. self._min_frame = 1
  106. def seek(self, layer):
  107. if not self._seek_check(layer):
  108. return
  109. # seek to given layer (1..max)
  110. try:
  111. name, mode, bbox, tile = self.layers[layer - 1]
  112. self.mode = mode
  113. self.tile = tile
  114. self.frame = layer
  115. self.fp = self.__fp
  116. return name, bbox
  117. except IndexError as e:
  118. raise EOFError("no such layer") from e
  119. def tell(self):
  120. # return layer number (0=image, 1..max=layers)
  121. return self.frame
  122. def load_prepare(self):
  123. # create image memory if necessary
  124. if not self.im or self.im.mode != self.mode or self.im.size != self.size:
  125. self.im = Image.core.fill(self.mode, self.size, 0)
  126. # create palette (optional)
  127. if self.mode == "P":
  128. Image.Image.load(self)
  129. def _close__fp(self):
  130. try:
  131. if self.__fp != self.fp:
  132. self.__fp.close()
  133. except AttributeError:
  134. pass
  135. finally:
  136. self.__fp = None
  137. def _layerinfo(fp, ct_bytes):
  138. # read layerinfo block
  139. layers = []
  140. def read(size):
  141. return ImageFile._safe_read(fp, size)
  142. ct = i16(read(2))
  143. # sanity check
  144. if ct_bytes < (abs(ct) * 20):
  145. raise SyntaxError("Layer block too short for number of layers requested")
  146. for i in range(abs(ct)):
  147. # bounding box
  148. y0 = i32(read(4))
  149. x0 = i32(read(4))
  150. y1 = i32(read(4))
  151. x1 = i32(read(4))
  152. # image info
  153. info = []
  154. mode = []
  155. ct_types = i16(read(2))
  156. types = list(range(ct_types))
  157. if len(types) > 4:
  158. continue
  159. for i in types:
  160. type = i16(read(2))
  161. if type == 65535:
  162. m = "A"
  163. else:
  164. m = "RGBA"[type]
  165. mode.append(m)
  166. size = i32(read(4))
  167. info.append((m, size))
  168. # figure out the image mode
  169. mode.sort()
  170. if mode == ["R"]:
  171. mode = "L"
  172. elif mode == ["B", "G", "R"]:
  173. mode = "RGB"
  174. elif mode == ["A", "B", "G", "R"]:
  175. mode = "RGBA"
  176. else:
  177. mode = None # unknown
  178. # skip over blend flags and extra information
  179. read(12) # filler
  180. name = ""
  181. size = i32(read(4)) # length of the extra data field
  182. combined = 0
  183. if size:
  184. data_end = fp.tell() + size
  185. length = i32(read(4))
  186. if length:
  187. fp.seek(length - 16, io.SEEK_CUR)
  188. combined += length + 4
  189. length = i32(read(4))
  190. if length:
  191. fp.seek(length, io.SEEK_CUR)
  192. combined += length + 4
  193. length = i8(read(1))
  194. if length:
  195. # Don't know the proper encoding,
  196. # Latin-1 should be a good guess
  197. name = read(length).decode("latin-1", "replace")
  198. combined += length + 1
  199. fp.seek(data_end)
  200. layers.append((name, mode, (x0, y0, x1, y1)))
  201. # get tiles
  202. i = 0
  203. for name, mode, bbox in layers:
  204. tile = []
  205. for m in mode:
  206. t = _maketile(fp, m, bbox, 1)
  207. if t:
  208. tile.extend(t)
  209. layers[i] = name, mode, bbox, tile
  210. i += 1
  211. return layers
  212. def _maketile(file, mode, bbox, channels):
  213. tile = None
  214. read = file.read
  215. compression = i16(read(2))
  216. xsize = bbox[2] - bbox[0]
  217. ysize = bbox[3] - bbox[1]
  218. offset = file.tell()
  219. if compression == 0:
  220. #
  221. # raw compression
  222. tile = []
  223. for channel in range(channels):
  224. layer = mode[channel]
  225. if mode == "CMYK":
  226. layer += ";I"
  227. tile.append(("raw", bbox, offset, layer))
  228. offset = offset + xsize * ysize
  229. elif compression == 1:
  230. #
  231. # packbits compression
  232. i = 0
  233. tile = []
  234. bytecount = read(channels * ysize * 2)
  235. offset = file.tell()
  236. for channel in range(channels):
  237. layer = mode[channel]
  238. if mode == "CMYK":
  239. layer += ";I"
  240. tile.append(("packbits", bbox, offset, layer))
  241. for y in range(ysize):
  242. offset = offset + i16(bytecount, i)
  243. i += 2
  244. file.seek(offset)
  245. if offset & 1:
  246. read(1) # padding
  247. return tile
  248. # --------------------------------------------------------------------
  249. # registry
  250. Image.register_open(PsdImageFile.format, PsdImageFile, _accept)
  251. Image.register_extension(PsdImageFile.format, ".psd")
  252. Image.register_mime(PsdImageFile.format, "image/vnd.adobe.photoshop")