【问题标题】:How do I convert a base64 image?如何转换 base64 图像?
【发布时间】:2015-12-18 08:15:08
【问题描述】:

我正在尝试使用 ImageMagick 的“转换”命令行工具。我有一个 base64 编码的 png 文件,我需要将其转换为另一种格式。我正在查看documentationforum discussion,这表明我应该能够使用这种语法:

convert inline:file.txt file.jpg

但是当我这样做时,我会收到以下错误消息:

convert: corrupt image `file.txt' @ error/constitute.c/ReadInlineImage/910.

我做错了什么?如何转换为读取 base64 图像文件?

【问题讨论】:

    标签: imagemagick imagemagick-convert


    【解决方案1】:

    更新答案 - 现在我自己更了解了 :-)

    基本上,您可以像这样使用openssl 对图像进行base64 编码:

    openssl enc -base64 -in image.png > image.b64
    

    但是,如果您希望 ImageMagick 能够阅读它,则需要在开头添加一个小标题,以告诉 ImageMagick 后面的内容。标头必须包含:

    data:image/png;base64,
    

    后面是使用上述openssl 命令生成的base64 编码数据。因此,根据您的 shell 具有的功能,您可以使用 bash 中的复合语句来执行此操作:

    { echo "data:image/png;base64,"; openssl enc -base64 -in input.png; } > image.b64
    

    或在 Windows 中这样:

    echo data:image/png;base64,         > image.b64
    openssl enc -base64 -in image.png  >> image.b64
    

    获得该格式的图像后,您可以继续使用ImageMagick 处理它,如下所示:

    convert inline:image.b64 result.png
    

    在css中使用这个的,在一行输出中添加-A标志

    openssl enc -base64 -A -in image.png > image.b64
    

    原答案

    经过多次试验,我可以做到!!! :-)

    从 Eric (@emcconville) 的设置开始:

    # For example
    convert rose: rose.png
    # Create base64 file
    openssl enc -base64 -in rose.png -out rose.txt
    

    现在将这个混乱添加到最后一行:

    { echo "data:image/png;base64,"; cat rose.txt; } | convert inline:- out.jpg
    

    我猜data:image/png;base64, 不存在于openssl 创建的base64 文件中,所以我创建了一个复合语句,将其连同文件发送到ImageMagickstdin

    【讨论】:

      【解决方案2】:

      更新答案

      来自 ImageMagick format docs...

      内嵌图像类似于inline:data:;base64,/9j/4AAQSk...knrn//2Q==。如果内嵌图像超过 5000 个字符,请从文件中引用它(例如 inline:inline.txt)。

      当使用内联格式时,这暗示了两个“陷阱”。首先,应该删除任何标准的 base64 空格(unix 换行符),以便所有信息都在一行上。其次,应该从文件缓冲区中读取任何超过 5000 个字符的数据。

      # Copy data to new file, striping line-breaks & adding INLINE header. (Please advise better sed/awk.)
      cat file.txt | tr -d "\r\n" | awk '{print "data:image/png;base64,"$1}' > file.inline
      # Read file as expected
      convert inline:file.inline file.jpg
      

      原始(并非真正正确)答案

      “损坏的图像”消息告诉我 base64 文件中可能有空格。如果是这样, 实用程序将起作用。

      # For example
      convert rose: rose.png
      # Create base64 file
      openssl enc -base64 -in rose.png -out rose.txt
      # Read inline & data from stdin -- after stripping whitespace
      cat rose.txt | tr -d "\r\n" | convert inline:data:- out.jpg
      

      【讨论】:

      • 恐怕这给了我基本相同的错误:“转换:损坏的图像`数据:-'@错误/构成.c/ReadInlineImage/910。”除了行尾(unix)之外,我在原始文件中看不到任何空格。
      • 你能从新图像中重新创建相同的消息吗?
      • 是的,我使用任何 base64 图像都能获得它。
      • 我不明白应该如何使用该语法,否则它根本不起作用。在网上找不到任何关于如何使用 convert 读取 base64 图像文件的明确示例。
      • 好的,更新了答案。 @MarkSetchell 请随时根据需要进行简化。
      猜你喜欢
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      相关资源
      最近更新 更多