解决思路:利用 commons-exec 的包,使用 CommandLine 调用ghostscript处理

  1. pom 引用追加
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.3</version>
</dependency>
  1. 创建工具类
public class ImageUtil {

    private static Logger log = LoggerFactory.getLogger(ImageUtil.class);

    private static final String OS_NAME = "os.name";

    private static final String WINDOWS = "Windows";

    private static final String MAC = "Mac";


    public static void convertEpsToJpg(String epsFilePath, String jpgFilePath) {

        try {

            GsProperties gsProperties = SpringBootUtil.getBean(GsProperties.class);

            String executable = null;

            String osName = System.getProperty(OS_NAME);
            if (osName.startsWith(WINDOWS)) {
                executable = gsProperties.getWin();
            } else if (osName.startsWith(MAC)) {
                executable = gsProperties.getMac();
            } else {
                executable = gsProperties.getLinux();
            }

            ByteArrayOutputStream stdout = new ByteArrayOutputStream();
            PumpStreamHandler psh = new PumpStreamHandler(stdout, stdout);

            CommandLine cl = CommandLine.parse(executable);
            cl.addArgument("-sDEVICE=jpeg");
            cl.addArgument("-dEPSFitPage");
            cl.addArgument("-dJPEGQ=100");
            cl.addArgument("-dNOPAUSE");
            cl.addArgument("-dBATCH");
            cl.addArgument("-sOutputFile=" + jpgFilePath);
            cl.addArgument(epsFilePath);
            log.info(cl.toString());

            DefaultExecutor exec = new DefaultExecutor();
            exec.setStreamHandler(psh);

            ExecuteWatchdog watchdog = new ExecuteWatchdog(2000);//设置超时时间(毫秒)
            exec.setWatchdog(watchdog);

            exec.execute(cl);
            log.info(stdout.toString());

        } catch (Exception e) {
            log.error("eps to jpg 失败:" + e.toString());
        }


    }

}
  1. GsProperties 配置项
gs:
  win: C:*******
  linux: /usr/bin/gs
  mac: /opt/homebrew/bin/gs

Start_liyi
29 声望3 粉丝

I'm 小兵