You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Ghostscript批量将多个PostScript文件转换为PNG?

批量将PostScript文件转换为PNG的问题与解决方法

问题描述

需要处理数百个后缀为_rss.ps的PostScript文件,用Ghostscript批量转PNG。手动单文件转换命令可正常运行:

gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r900 -GraphicsAlphaBits=4 -sOutputFile=output.png input.ps

编写的Bash脚本带echo时能输出正确转换命令,但移除echo和引号执行时,Ghostscript报语法错误:

GPL Ghostscript 9.25 (2018-09-13)
Copyright (C) 2018 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Error: /syntaxerror in (binary token, type=137)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push   2047   1   3   %oparray_pop   2046   1   3   %oparray_pop   2026   1   3   %oparray_pop   1884   1   3   %oparray_pop   --nostringval--   %errorexec_pop   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push
Dictionary stack:
   --dict:953/1684(ro)(G)--   --dict:0/20(G)--   --dict:77/200(L)--
Current allocation mode is local
GPL Ghostscript 9.25: Unrecoverable error, exit code 1

错误原因与修正脚本

报错核心原因是文件名包含空格或特殊字符,Shell解析时会拆分文件名,导致Ghostscript收到不完整的文件路径。修正方法是给变量加上双引号,确保文件名被当作整体传递:

#!/bin/bash
for i in *_rss.ps ; do
    gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r900 -GraphicsAlphaBits=4 -sOutputFile="${i/_rss.ps/_rss.png}" "$i"
done
  • 给${i/_rss.ps/_rss.png}和$i都加上双引号,避免特殊字符引发的解析错误
  • 移除echo后直接执行即可,无需额外引号包裹整个命令

其他批量处理方法

方法1:用xargs简化命令

无需编写脚本,一行命令即可完成批量转换:

ls *_rss.ps | xargs -I {} gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r900 -GraphicsAlphaBits=4 -sOutputFile="{/_rss.ps/_rss.png}" {}
  • -I {}指定替换符,{/_rss.ps/_rss.png}会自动替换文件名后缀

方法2:用find递归处理子目录文件

如果需要处理子目录中的_rss.ps文件,用find更合适:

find . -name "*_rss.ps" -exec bash -c 'gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r900 -GraphicsAlphaBits=4 -sOutputFile="${0/_rss.ps/_rss.png}" "$0"' {} \;

内容的提问来源于stack exchange,提问作者Amy H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:53:17