如何转换base64图像? [英] How do I convert a base64 image?
问题描述
我正在尝试使用ImageMagick中的convert命令行工具。我有一个base64编码的png文件,我需要将其转换为另一种格式。我正在查看文档和论坛讨论,这表明我应该可以使用这种语法:
I am trying to use the "convert" command-line tool from ImageMagick. I have a base64 encoded png file and I need to convert it to another format. I am looking at documentation and a forum discussion which suggests that I should be able to use this syntax:
convert inline:file.txt file.jpg
但是,当我这样做时,我收到此错误消息:
But when I do this, I get this error message:
convert: corrupt image `file.txt' @ error/constitute.c/ReadInlineImage/910.
我做错了什么?如何转换为读取base64图像文件?
What am I doing wrong? How do I get convert to read a base64 image file?
推荐答案
更新答案 - 现在我自己更好地理解: - )
Updated Answer - now that I understand it better myself :-)
基本上,您可以使用 openssl
对此图像进行base64编码,如下所示:
Basically, you can base64 encode an image using openssl
like this:
openssl enc -base64 -in image.png > image.b64
但是,如果你想要 ImageMagick
为了能够阅读它,你需要一个小的标题,告诉 ImageMagick
接下来的内容。标题必须包含:
However, if you want ImageMagick
to be able to read it, you need a small header at the start, to tell ImageMagick
what follows. The header must contain:
data:image/png;base64,
后面是使用上面的 openssl
命令生成的base64编码数据。所以,根据shell的功能,你可以在 bash
中使用复合语句这样做:
followed by your base64 encoded data generated using the openssl
command above. So, depending on what features your shell has, you could do it like this with a compound statement in bash
:
{ echo "data:image/png;base64,"; openssl enc -base64 -in input.png; } > image.b64
或在Windows中这样:
or like this in Windows:
echo data:image/png;base64, > image.b64
openssl enc -base64 -in image.png >> image.b64
一旦你有了那种格式的图像,你就可以继续处理它了 ImageMagick
喜欢这样:
Once you have the image in that format, you can then proceed to process it with ImageMagick
like this:
convert inline:image.b64 result.png
对于在css中使用此功能的用户,请添加 -A
标记为一行输出
For those who use this in css, add -A
flag to output in one line
openssl enc -base64 -A -in image.png > image.b64
原始答案
经过多次试验,我可以做到! : - )
After MUCH experimenting, I can do it!!! :-)
从Eric(@emcconville)设置开始:
Start with Eric's (@emcconville) setup:
# For example
convert rose: rose.png
# Create base64 file
openssl enc -base64 -in rose.png -out rose.txt
现在将这个混乱添加为最后一行:
and now add this mess as the last line:
{ echo "data:image/png;base64,"; cat rose.txt; } | convert inline:- out.jpg
我想数据:image / png ; base64,
不存在于由 openssl
创建的base64文件中,因此我创建了一个复合语句,将该文件加上 stdin
ImageMagick
。
I guess the data:image/png;base64,
is not present in the base64 file created by openssl
so I create a compound statement that sends that plus the file to stdin
of ImageMagick
.
这篇关于如何转换base64图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!