【发布时间】:2015-01-18 22:17:09
【问题描述】:
对于一个附带项目,我正在尝试制作一个带有 2 个参数的简单可执行文件:
- 文本文件路径(包含 Base64 编码的动画 GIF)(例如 base.txt)
- 要导出的 GIF 的名称(例如 hello.gif)
我认为这一切都应该是这样的:
- 它打开并从文件中读取数据
- 它获取数据并解码 Base64 字符串
- 然后将数据保存为动画 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.Length、imageData[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