EpsImagePlugin.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # EPS file handling
  6. #
  7. # History:
  8. # 1995-09-01 fl Created (0.1)
  9. # 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
  10. # 1996-08-22 fl Don't choke on floating point BoundingBox values
  11. # 1996-08-23 fl Handle files from Macintosh (0.3)
  12. # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
  13. # 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
  14. # 2014-05-07 e Handling of EPS with binary preview and fixed resolution
  15. # resizing
  16. #
  17. # Copyright (c) 1997-2003 by Secret Labs AB.
  18. # Copyright (c) 1995-2003 by Fredrik Lundh
  19. #
  20. # See the README file for information on usage and redistribution.
  21. #
  22. from __future__ import annotations
  23. __lazy_modules__ = {"PIL._binary", "io", "subprocess"}
  24. import io
  25. import os
  26. import re
  27. import subprocess
  28. import sys
  29. from . import Image, ImageFile
  30. from ._binary import i32le as i32
  31. TYPE_CHECKING = False
  32. if TYPE_CHECKING:
  33. from typing import IO
  34. # --------------------------------------------------------------------
  35. split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
  36. field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
  37. gs_binary: str | bool | None = None
  38. gs_windows_binary = None
  39. def has_ghostscript() -> bool:
  40. global gs_binary, gs_windows_binary
  41. if gs_binary is None:
  42. if sys.platform.startswith("win"):
  43. if gs_windows_binary is None:
  44. import shutil
  45. for binary in ("gswin32c", "gswin64c", "gs"):
  46. if shutil.which(binary) is not None:
  47. gs_windows_binary = binary
  48. break
  49. else:
  50. gs_windows_binary = False
  51. gs_binary = gs_windows_binary
  52. else:
  53. try:
  54. subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
  55. gs_binary = "gs"
  56. except OSError:
  57. gs_binary = False
  58. return gs_binary is not False
  59. def Ghostscript(
  60. tile: list[ImageFile._Tile],
  61. size: tuple[int, int],
  62. fp: IO[bytes],
  63. scale: int = 1,
  64. transparency: bool = False,
  65. ) -> Image.core.ImagingCore:
  66. """Render an image using Ghostscript"""
  67. global gs_binary
  68. if not has_ghostscript():
  69. msg = "Unable to locate Ghostscript on paths"
  70. raise OSError(msg)
  71. assert isinstance(gs_binary, str)
  72. # Unpack decoder tile
  73. args = tile[0].args
  74. assert isinstance(args, tuple)
  75. length, bbox = args
  76. # Hack to support hi-res rendering
  77. scale = int(scale) or 1
  78. width = size[0] * scale
  79. height = size[1] * scale
  80. Image._decompression_bomb_check((width, height))
  81. # resolution is dependent on bbox and size
  82. res_x = 72.0 * width / (bbox[2] - bbox[0])
  83. res_y = 72.0 * height / (bbox[3] - bbox[1])
  84. import tempfile
  85. out_fd, outfile = tempfile.mkstemp()
  86. os.close(out_fd)
  87. infile_temp = None
  88. if hasattr(fp, "name") and os.path.exists(fp.name):
  89. # Make the path absolute so that a filename beginning with "-" or "@"
  90. # can never be interpreted by Ghostscript's argument parser
  91. # as an option or an @-file token
  92. infile = os.path.abspath(fp.name)
  93. else:
  94. in_fd, infile_temp = tempfile.mkstemp()
  95. os.close(in_fd)
  96. infile = infile_temp
  97. # Ignore length and offset!
  98. # Ghostscript can read it
  99. # Copy whole file to read in Ghostscript
  100. with open(infile_temp, "wb") as f:
  101. # fetch length of fp
  102. fp.seek(0, io.SEEK_END)
  103. fsize = fp.tell()
  104. # ensure start position
  105. # go back
  106. fp.seek(0)
  107. lengthfile = fsize
  108. while lengthfile > 0:
  109. s = fp.read(min(lengthfile, 100 * 1024))
  110. if not s:
  111. break
  112. lengthfile -= len(s)
  113. f.write(s)
  114. if transparency:
  115. # "RGBA"
  116. device = "pngalpha"
  117. else:
  118. # "pnmraw" automatically chooses between
  119. # PBM ("1"), PGM ("L"), and PPM ("RGB").
  120. device = "pnmraw"
  121. # Build Ghostscript command
  122. command = [
  123. gs_binary,
  124. "-q", # quiet mode
  125. f"-g{width:d}x{height:d}", # set output geometry (pixels)
  126. f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch)
  127. "-dBATCH", # exit after processing
  128. "-dNOPAUSE", # don't pause between pages
  129. "-dSAFER", # safe mode
  130. f"-sDEVICE={device}",
  131. f"-sOutputFile={outfile}", # output file
  132. # adjust for image origin
  133. "-c",
  134. f"{-bbox[0]} {-bbox[1]} translate",
  135. "-f",
  136. infile, # input file
  137. # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
  138. "-c",
  139. "showpage",
  140. ]
  141. # push data through Ghostscript
  142. try:
  143. startupinfo = None
  144. if sys.platform.startswith("win"):
  145. startupinfo = subprocess.STARTUPINFO()
  146. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  147. subprocess.check_call(command, startupinfo=startupinfo)
  148. with Image.open(outfile) as out_im:
  149. out_im.load()
  150. return out_im.im.copy()
  151. finally:
  152. try:
  153. os.unlink(outfile)
  154. if infile_temp:
  155. os.unlink(infile_temp)
  156. except OSError:
  157. pass
  158. def _accept(prefix: bytes) -> bool:
  159. return prefix.startswith(b"%!PS") or (
  160. len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5
  161. )
  162. ##
  163. # Image plugin for Encapsulated PostScript. This plugin supports only
  164. # a few variants of this format.
  165. class EpsImageFile(ImageFile.ImageFile):
  166. """EPS File Parser for the Python Imaging Library"""
  167. format = "EPS"
  168. format_description = "Encapsulated Postscript"
  169. mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
  170. def _open(self) -> None:
  171. assert self.fp is not None
  172. length, offset = self._find_offset(self.fp)
  173. # go to offset - start of "%!PS"
  174. self.fp.seek(offset)
  175. self._mode = "RGB"
  176. # When reading header comments, the first comment is used.
  177. # When reading trailer comments, the last comment is used.
  178. bounding_box: list[int] | None = None
  179. imagedata_size: tuple[int, int] | None = None
  180. byte_arr = bytearray(255)
  181. bytes_mv = memoryview(byte_arr)
  182. bytes_read = 0
  183. reading_header_comments = True
  184. reading_trailer_comments = False
  185. trailer_reached = False
  186. def check_required_header_comments() -> None:
  187. """
  188. The EPS specification requires that some headers exist.
  189. This should be checked when the header comments formally end,
  190. when image data starts, or when the file ends, whichever comes first.
  191. """
  192. if "PS-Adobe" not in self.info:
  193. msg = 'EPS header missing "%!PS-Adobe" comment'
  194. raise SyntaxError(msg)
  195. if "BoundingBox" not in self.info:
  196. msg = 'EPS header missing "%%BoundingBox" comment'
  197. raise SyntaxError(msg)
  198. def read_comment(s: str) -> bool:
  199. nonlocal bounding_box, reading_trailer_comments
  200. try:
  201. m = split.match(s)
  202. except re.error as e:
  203. msg = "not an EPS file"
  204. raise SyntaxError(msg) from e
  205. if not m:
  206. return False
  207. k, v = m.group(1, 2)
  208. self.info[k] = v
  209. if k == "BoundingBox":
  210. if v == "(atend)":
  211. reading_trailer_comments = True
  212. elif not bounding_box or (trailer_reached and reading_trailer_comments):
  213. try:
  214. # Note: The DSC spec says that BoundingBox
  215. # fields should be integers, but some drivers
  216. # put floating point values there anyway.
  217. bounding_box = [int(float(i)) for i in v.split()]
  218. except Exception:
  219. pass
  220. return True
  221. while True:
  222. byte = self.fp.read(1)
  223. if byte == b"":
  224. # if we didn't read a byte we must be at the end of the file
  225. if bytes_read == 0:
  226. if reading_header_comments:
  227. check_required_header_comments()
  228. break
  229. elif byte in b"\r\n":
  230. # if we read a line ending character, ignore it and parse what
  231. # we have already read. if we haven't read any other characters,
  232. # continue reading
  233. if bytes_read == 0:
  234. continue
  235. else:
  236. # ASCII/hexadecimal lines in an EPS file must not exceed
  237. # 255 characters, not including line ending characters
  238. if bytes_read >= 255:
  239. # only enforce this for lines starting with a "%",
  240. # otherwise assume it's binary data
  241. if byte_arr[0] == ord("%"):
  242. msg = "not an EPS file"
  243. raise SyntaxError(msg)
  244. else:
  245. if reading_header_comments:
  246. check_required_header_comments()
  247. reading_header_comments = False
  248. # reset bytes_read so we can keep reading
  249. # data until the end of the line
  250. bytes_read = 0
  251. byte_arr[bytes_read] = byte[0]
  252. bytes_read += 1
  253. continue
  254. if reading_header_comments:
  255. # Load EPS header
  256. # if this line doesn't start with a "%",
  257. # or does start with "%%EndComments",
  258. # then we've reached the end of the header/comments
  259. if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
  260. check_required_header_comments()
  261. reading_header_comments = False
  262. continue
  263. s = str(bytes_mv[:bytes_read], "latin-1")
  264. if not read_comment(s):
  265. m = field.match(s)
  266. if m:
  267. k = m.group(1)
  268. if k.startswith("PS-Adobe"):
  269. self.info["PS-Adobe"] = k[9:]
  270. else:
  271. self.info[k] = ""
  272. elif s[0] == "%":
  273. # handle non-DSC PostScript comments that some
  274. # tools mistakenly put in the Comments section
  275. pass
  276. else:
  277. msg = "bad EPS header"
  278. raise OSError(msg)
  279. elif bytes_mv[:11] == b"%ImageData:":
  280. # Check for an "ImageData" descriptor
  281. # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
  282. # If we've already read an "ImageData" descriptor,
  283. # don't read another one.
  284. if imagedata_size:
  285. bytes_read = 0
  286. continue
  287. # Values:
  288. # columns
  289. # rows
  290. # bit depth (1 or 8)
  291. # mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
  292. # number of padding channels
  293. # block size (number of bytes per row per channel)
  294. # binary/ascii (1: binary, 2: ascii)
  295. # data start identifier (the image data follows after a single line
  296. # consisting only of this quoted value)
  297. image_data_values = byte_arr[11:bytes_read].split(None, 7)
  298. columns, rows, bit_depth, mode_id = (
  299. int(value) for value in image_data_values[:4]
  300. )
  301. if bit_depth == 1:
  302. self._mode = "1"
  303. elif bit_depth == 8:
  304. try:
  305. self._mode = self.mode_map[mode_id]
  306. except ValueError:
  307. break
  308. else:
  309. break
  310. # Parse the columns and rows after checking the bit depth and mode
  311. # in case the bit depth and/or mode are invalid.
  312. imagedata_size = columns, rows
  313. elif bytes_mv[:5] == b"%%EOF":
  314. break
  315. elif trailer_reached and reading_trailer_comments:
  316. # Load EPS trailer
  317. s = str(bytes_mv[:bytes_read], "latin-1")
  318. read_comment(s)
  319. elif bytes_mv[:9] == b"%%Trailer":
  320. trailer_reached = True
  321. elif bytes_mv[:14] == b"%%BeginBinary:":
  322. bytecount = int(byte_arr[14:bytes_read])
  323. if bytecount < 0:
  324. msg = "BeginBinary bytecount cannot be negative"
  325. raise ValueError(msg)
  326. self.fp.seek(bytecount, os.SEEK_CUR)
  327. bytes_read = 0
  328. # A "BoundingBox" is always required,
  329. # even if an "ImageData" descriptor size exists.
  330. if not bounding_box:
  331. msg = "cannot determine EPS bounding box"
  332. raise OSError(msg)
  333. # An "ImageData" size takes precedence over the "BoundingBox".
  334. self._size = imagedata_size or (
  335. bounding_box[2] - bounding_box[0],
  336. bounding_box[3] - bounding_box[1],
  337. )
  338. self.tile = [
  339. ImageFile._Tile("eps", (0, 0, *self.size), offset, (length, bounding_box))
  340. ]
  341. def _find_offset(self, fp: IO[bytes]) -> tuple[int, int]:
  342. s = fp.read(4)
  343. if s == b"%!PS":
  344. # for HEAD without binary preview
  345. fp.seek(0, io.SEEK_END)
  346. length = fp.tell()
  347. offset = 0
  348. elif i32(s) == 0xC6D3D0C5:
  349. # FIX for: Some EPS file not handled correctly / issue #302
  350. # EPS can contain binary data
  351. # or start directly with latin coding
  352. # more info see:
  353. # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
  354. s = fp.read(8)
  355. offset = i32(s)
  356. length = i32(s, 4)
  357. else:
  358. msg = "not an EPS file"
  359. raise SyntaxError(msg)
  360. return length, offset
  361. def load(
  362. self, scale: int = 1, transparency: bool = False
  363. ) -> Image.core.PixelAccess | None:
  364. # Load EPS via Ghostscript
  365. if self.tile:
  366. assert self.fp is not None
  367. self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
  368. self._mode = self.im.mode
  369. self._size = self.im.size
  370. self.tile = []
  371. return Image.Image.load(self)
  372. def load_seek(self, pos: int) -> None:
  373. # we can't incrementally load, so force ImageFile.parser to
  374. # use our custom load method by defining this method.
  375. pass
  376. # --------------------------------------------------------------------
  377. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None:
  378. """EPS Writer for the Python Imaging Library."""
  379. # make sure image data is available
  380. im.load()
  381. # determine PostScript image mode
  382. if im.mode == "L":
  383. operator = (8, 1, b"image")
  384. elif im.mode == "RGB":
  385. operator = (8, 3, b"false 3 colorimage")
  386. elif im.mode == "CMYK":
  387. operator = (8, 4, b"false 4 colorimage")
  388. else:
  389. msg = "image mode is not supported"
  390. raise ValueError(msg)
  391. if eps:
  392. # write EPS header
  393. fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
  394. fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
  395. # fp.write("%%CreationDate: %s"...)
  396. fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
  397. fp.write(b"%%Pages: 1\n")
  398. fp.write(b"%%EndComments\n")
  399. fp.write(b"%%Page: 1 1\n")
  400. fp.write(b"%%ImageData: %d %d " % im.size)
  401. fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
  402. # image header
  403. fp.write(b"gsave\n")
  404. fp.write(b"10 dict begin\n")
  405. fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
  406. fp.write(b"%d %d scale\n" % im.size)
  407. fp.write(b"%d %d 8\n" % im.size) # <= bits
  408. fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
  409. fp.write(b"{ currentfile buf readhexstring pop } bind\n")
  410. fp.write(operator[2] + b"\n")
  411. if hasattr(fp, "flush"):
  412. fp.flush()
  413. ImageFile._save(im, fp, [ImageFile._Tile("eps", (0, 0, *im.size))])
  414. fp.write(b"\n%%%%EndBinary\n")
  415. fp.write(b"grestore end\n")
  416. if hasattr(fp, "flush"):
  417. fp.flush()
  418. # --------------------------------------------------------------------
  419. Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
  420. Image.register_save(EpsImageFile.format, _save)
  421. Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
  422. Image.register_mime(EpsImageFile.format, "application/postscript")