在命令行中将 SVG 绘图裁剪为画布大小

div*_*nov 9 command-line image-manipulation svg inkscape

我有 PlantUML 生成的 SVG 图像,其中有一些在画布之外绘图的部分。这使得使用此类图像变得困难,我需要将绘图裁剪为画布大小。无论如何,当我用脚本生成 UML 图时,在那里执行裁剪也会非常有效。

到目前为止,我已经尝试了两件事:a) 使用 Inkscape 调整画布大小以进行绘图

inkscape --verb=FitCanvasToDrawing --verb=FileSave --verb=FileClose *.svg
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我需要将绘图裁剪为画布大小,并且此操作似乎不可用。

b) 使用 rsvg-convert 调整大小

rsvg-convert image.svg -w 1870 -h 1195 -f svg -o image.svg
Run Code Online (Sandbox Code Playgroud)

这确实裁剪到所需的大小,但图像大小增加了约 10 倍,因为现在有一些二进制图像嵌入到 SVG 中。这对我来说是不可接受的。

div*_*nov 5

我找到了一种使用 orion 的提议的不优雅的方法来做到这一点。假设$svg_file_name是一个包含 SVG 图像文件路径的变量。

首先我们需要图片的宽度和高度

width=$(exiftool -ImageWidth $svg_file_name | sed "s/.*: //;s/pt//g")
height=$(exiftool -ImageHeight $svg_file_name | sed "s/.*: //;s/pt//g")
Run Code Online (Sandbox Code Playgroud)

PlantUML 将图表生成为单个组(标签<g>),让我们将画布大小的矩形放在该组上

sed -i "s|</g>|</g><polygon fill=\"#FFFFFF\" points=\"0,0,0,$height,$width,$height,$width,0\" style=\"stroke: #000000; stroke-width: 1.0;\"/>|" $svg_file_name
Run Code Online (Sandbox Code Playgroud)

现在用inkscape打开图像,全选并用矩形裁剪组

inkscape --verb=EditSelectAll --verb=ObjectSetClipPath --verb=FileSave --verb=FileClose $svg_file_name
Run Code Online (Sandbox Code Playgroud)

使用最新的 Inkscape 需要退出 Inkscape 而不是关闭文件

inkscape --verb=EditSelectAll --verb=ObjectSetClipPath --verb=FileSave --verb=FileQuit $svg_file_name
Run Code Online (Sandbox Code Playgroud)