【问题标题】:Converting Base64 string to GIF image将 Base64 字符串转换为 GIF 图像
【发布时间】:2015-01-18 22:17:09
【问题描述】:

对于一个附带项目,我正在尝试制作一个带有 2 个参数的简单可执行文件:

  1. 文本文件路径(包含 Base64 编码的动画 GIF)(例如 base.txt)
  2. 要导出的 GIF 的名称(例如 hello.gif)

我认为这一切都应该是这样的:

  1. 它打开并从文件中读取数据
  2. 它获取数据并解码 Base64 字符串
  3. 然后将数据保存为动画 GIF

现在当然有一些中间步骤需要完成,但我认为我目前不需要介绍这些步骤。

所以最后我留下了以下 C# 文件,它应该可以做我想做的事情。

using System;
using System.Drawing;
using System.Text;
using System.IO;

namespace Base642Img
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            if (args.Length == 2) {
                byte[] buffer;
                String imageData;
                FileStream fileStream = new FileStream (args [0], FileMode.Open, FileAccess.Read);

                try {
                    int length = (int)fileStream.Length;
                    buffer = new byte[length];
                    int count;
                    int sum = 0;

                    while ((count = fileStream.Read (buffer, sum, length - sum)) > 0) {
                        sum += count;
                    }
                } finally {
                    fileStream.Close();
                }

                try{
                    imageData = Encoding.UTF8.GetString (buffer, 0, buffer.Length);
                    imageData = imageData.Replace (System.Environment.NewLine, "");

                    byte[] imageBytes = System.Convert.FromBase64String (imageData);

                    MemoryStream ms = new MemoryStream (imageBytes, 0, imageBytes.Length);
                    ms.Write (imageBytes, 0, imageBytes.Length);

                    Image image = Image.FromStream (ms, true);
                    image.Save (args [1], System.Drawing.Imaging.ImageFormat.Gif);
                } catch (Exception e) {
                    Console.WriteLine (e.ToString ());
                }
            } else {
                Console.WriteLine ("Incorrect number of arguments");
            }
        }
    }
}

这在 MonoDevelop 中构建得非常好。但是当我去运行文件时(给定两个参数)它会吐出以下异常:

System.FormatException: Invalid length.
  at (wrapper managed-to-native) System.Convert:InternalFromBase64String (string,bool)
  at System.Convert.FromBase64String (System.String s) [0x00000] in <filename unknown>:0 
  at Base642Img.MainClass.Main (System.String[] args) [0x00000] in <filename unknown>:0 

我完全不知道这是在说什么,而且我在 Google 上的所有搜索都变成了空白,所以我现在求助于 Stack Overflow,希望有人可以帮助我。

【问题讨论】:

  • 表示imageData不包含有效的base 64编码字符串。
  • 但它确实 o.O.所有预先存在的转换器都可以很好地从文件中读取数据。阅读它时我可能做错了什么使字符串无效?
  • 就在该行执行之前,您能调试一下imageData.LengthimageData[0]imageData[1]imageData[imageData.Length - 2]imageData[imageData.Length - 1] 的值吗?
  • 好像你把事情弄复杂了,var imageBytes = Convert.FromBase64String(File.ReadAllText(filename)); this.image = Image.FromStream(new MemoryStream(imageBytes));
  • @Michæl Liu 按顺序:516838, R, 0, O, w

标签: c# image mono base64 animated-gif


【解决方案1】:

Convert.FromBase64String 要求输入字符串在末尾最多填充两个= 字符,以便其总长度(忽略空白字符)是四的倍数。显然,创建 base 64 编码文件的程序省略了尾随填充。

您需要根据需要自己附加缺少的填充字符:

// using System.Collections.Generic;
// using System.Linq;

string imageData = File.ReadAllText(args[0]);
HashSet<char> whiteSpace = new HashSet<char> { '\t', '\n', '\r', ' ' };
int length = imageData.Count(c => !whiteSpace.Contains(c));
if (length % 4 != 0)
    imageData += new string('=', 4 - length % 4); // Pad length to multiple of 4.
byte[] imageBytes = Convert.FromBase64String(imageData);
MemoryStream ms = new MemoryStream(imageBytes);
Image image = Image.FromStream(ms, true);
image.Save(args[1], System.Drawing.Imaging.ImageFormat.Gif);

注意:由于Convert.FromBase64String 会忽略空白字符,因此无需删除换行符。 (感谢 EZI 指出这一点。)

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2011-06-17
    • 1970-01-01
    相关资源
    最近更新 更多