Simplified code by writing bytes instead of using wrapping to write strings

This commit is contained in:
Andrew Murray 2021-04-25 14:40:02 +10:00
parent 9c06ce044c
commit ce3d69baf9

View File

@ -354,56 +354,46 @@ def _save(im, fp, filename, eps=1):
# #
# determine PostScript image mode # determine PostScript image mode
if im.mode == "L": if im.mode == "L":
operator = (8, 1, "image") operator = (8, 1, b"image")
elif im.mode == "RGB": elif im.mode == "RGB":
operator = (8, 3, "false 3 colorimage") operator = (8, 3, b"false 3 colorimage")
elif im.mode == "CMYK": elif im.mode == "CMYK":
operator = (8, 4, "false 4 colorimage") operator = (8, 4, b"false 4 colorimage")
else: else:
raise ValueError("image mode is not supported") raise ValueError("image mode is not supported")
base_fp = fp if eps:
wrapped_fp = False
if fp != sys.stdout:
fp = io.TextIOWrapper(fp, encoding="latin-1")
wrapped_fp = True
try:
if eps:
#
# write EPS header
fp.write("%!PS-Adobe-3.0 EPSF-3.0\n")
fp.write("%%Creator: PIL 0.1 EpsEncode\n")
# fp.write("%%CreationDate: %s"...)
fp.write("%%%%BoundingBox: 0 0 %d %d\n" % im.size)
fp.write("%%Pages: 1\n")
fp.write("%%EndComments\n")
fp.write("%%Page: 1 1\n")
fp.write("%%ImageData: %d %d " % im.size)
fp.write('%d %d 0 1 1 "%s"\n' % operator)
# #
# image header # write EPS header
fp.write("gsave\n") fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
fp.write("10 dict begin\n") fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
fp.write(f"/buf {im.size[0] * operator[1]} string def\n") # fp.write("%%CreationDate: %s"...)
fp.write("%d %d scale\n" % im.size) fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
fp.write("%d %d 8\n" % im.size) # <= bits fp.write(b"%%Pages: 1\n")
fp.write(f"[{im.size[0]} 0 0 -{im.size[1]} 0 {im.size[1]}]\n") fp.write(b"%%EndComments\n")
fp.write("{ currentfile buf readhexstring pop } bind\n") fp.write(b"%%Page: 1 1\n")
fp.write(operator[2] + "\n") fp.write(b"%%ImageData: %d %d " % im.size)
if hasattr(fp, "flush"): fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
fp.flush()
ImageFile._save(im, base_fp, [("eps", (0, 0) + im.size, 0, None)]) #
# image header
fp.write(b"gsave\n")
fp.write(b"10 dict begin\n")
fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
fp.write(b"%d %d scale\n" % im.size)
fp.write(b"%d %d 8\n" % im.size) # <= bits
fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
fp.write(b"{ currentfile buf readhexstring pop } bind\n")
fp.write(operator[2] + b"\n")
if hasattr(fp, "flush"):
fp.flush()
fp.write("\n%%%%EndBinary\n") ImageFile._save(im, fp, [("eps", (0, 0) + im.size, 0, None)])
fp.write("grestore end\n")
if hasattr(fp, "flush"): fp.write(b"\n%%%%EndBinary\n")
fp.flush() fp.write(b"grestore end\n")
finally: if hasattr(fp, "flush"):
if wrapped_fp: fp.flush()
fp.detach()
# #