在 ImageMagick 中处理文本中撇号的正确方法是什么

问题描述

我有一个脚本,可以将 ImageMagick 命令行命令放在一起来处理 PDF 文档。这些最终会非常长,但这是一个这样的命令的代表性示例(为了可读性添加了行返回:

 magick.exe -density 300 -compress ZIP ( "c:\IMtemp\32.pdf[0]" -fill "#000" -stroke "#062430" -font Arial
 -pointsize 12 -draw "text 535,515 'This is my test text'") "c:\IMtemp\final.pdf"

该命令工作正常。但是,文本是动态的并且来自用户输入。如果用户要包含撇号,则命令行最终将是:

 magick.exe -density 300 -compress ZIP ( "c:\IMtemp\32.pdf[0]" -fill "#000" -stroke "#062430" -font Arial
 -pointsize 12 -draw "text 535,515 'This is my test text; it's just great'") "c:\IMtemp\final.pdf"

这当然会失败,因为撇号过早地结束了文本块。我的第一个想法是像这样逃避撇号:

 magick.exe -density 300 -compress ZIP ( "c:\IMtemp\32.pdf[0]" -fill "#000" -stroke "#062430" -font Arial
 -pointsize 12 -draw "text 535,515 'This is my test text; it\'s just great'") "c:\IMtemp\final.pdf"

但这行不通。相反,撇号被忽略,并出现文本“这是我的测试文本;它只是很棒”。然后我想也许我可以使用替代字符并尝试这样做:

 magick.exe -density 300 -compress ZIP ( "c:\IMtemp\32.pdf[0]" -fill "#000" -stroke "#062430" -font Arial
 -pointsize 12 -draw "text 535,515 'This is my test text; it’s just great'") "c:\IMtemp\final.pdf"

这导致文本“这是我的测试文本;它太棒了”,我认为是因为 IM 没有认为 UTF-8。我在文档中读到这可以通过向 IM 提供代码来规避并尝试过:

 magick.exe -density 300 -compress ZIP ( "c:\IMtemp\32.pdf[0]" -fill "#000" -stroke "#062430" -font Arial
 -pointsize 12 -draw "text 535,515 'This is my test text; it\u2019s just great'") "c:\IMtemp\final.pdf"

 magick.exe -density 300 -compress ZIP ( "c:\IMtemp\32.pdf[0]" -fill "#000" -stroke "#062430" -font Arial
 -pointsize 12 -draw "text 535,515 'This is my test text; it\x{2019}s just great'") "c:\IMtemp\final.pdf"

但这些只是将反斜杠后的所有内容显示为纯文本。

我不在乎撇号是如何保留的,只要其中的任何内容看起来正确到足以让人类可读且专业即可。我如何实现这一目标?

我在 lucee 服务器(在 Windows/IIS 上运行)上通过 cfExecute 运行 IM。

解决方法

在 Mac OSX Sierra 和 ImageMagick 7.0.11.3 上的 ImageMagick 中,卷曲单引号对我有用

magick -size 500x100 xc:white -fill "#000" -stroke "#062430" -font Arial -pointsize 18 \
-draw "text 30,30 'This is my test text; it’s just great'" x.png

enter image description here

,

您可以通过将注释文本从文件或从 stdin 输入 ImagMagick 来避免所有转义和引用问题。因此,如果您创建一个名为 "annotation.txt" 的文件,其中包含:

Weird stuff with ',@ and ".

您可以告诉 ImageMagick 从该文件中读取注释(使用 @filename)并将其放置在您的图像上,如下所示:

magick -size 640x240 xc:magenta -gravity center -pointsize 32 -annotate -40+90 @annotation.txt result.png

enter image description here


同样,如果您想通过其他命令将注释注入 ImageMagick,您可以告诉 ImageMagick 像这样读取它的 stdin:>

echo "Whatever @ '" | magick -size 640x240 xc:magenta -gravity center -pointsize 32 -annotate -40+90 @- result.png

enter image description here


正如 Fred 在评论中亲切提醒我的那样,您需要确保您的 policy.xml 文件允许这样做。它的位置可以通过以下方式找到:

identify -list configure | grep CONFIGURE_PATH

更多关于如何编辑和安全影响的讨论here