简体   繁体   中英

Changing output resolution when converting EPS file to PNG in Python Imaging Library

I wrote a simple implementation of PIL to convert a list of EPS files to PNG.

import Image
for infile in sys.argv[1:]:
    f, e = os.path.splitext(infile)
    outfile = f+".png"
    try:
        im = Image.open(infile)
        im.save(outfile, dpi = (1000, 1000))
    except IOError:
        print "Error"

Although the dpi flag changes the PNG's file resolution, it doesn't increase the resolution of the im object. This means my output PNG image has very low quality. Is there a way to increase the resolution of the im object? This code doesn't work.

im = Image.open(infile, dpi = (1000, 1000))

Ideas?

Looking at /usr/lib64/python2.7/site-packages/PIL/EpsImagePlugin.py this is implemented by calling ghostscript:

# Build ghostscript command
command = ["gs",
           "-q",                    # quite mode
           "-g%dx%d" % size,        # set output geometry (pixels)
           "-dNOPAUSE -dSAFER",     # don't pause between pages, safe mode
           "-sDEVICE=ppmraw",       # ppm driver
           "-sOutputFile=%s" % file,# output file
           "- >/dev/null 2>/dev/null"]

the size option only changes the figure size but does not rescale it. Maybe a bug report to the PIL developers would be useful here.

As workaround, and provided you have the ImageMagick commandline tools installed, you could use this as workaround:

import os
cmd = 'convert test.ps test.png'
os.system(cmd)

This works fine on my system, without loosing quality.

This version gives a bit more control on the resolution you obtain:

import os
cmd = "convert -density 300 test.ps test.png"
os.system(cmd)

Another work-around is to make the geometry or the text very large in the ps/eps. For my application, I'm rendering latex in EPS and converting to PNG. I simply set the font size to a larger number (200 pt) and the PNG quality is perfect. If you are generating the EPS content, this will work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM