C#无法使用内存流将字节数组转换为位图

时间:2018-09-25 09:35:57

标签: c# bitmap console memorystream

我一直在寻找几天,有关如何转换填充imageData的byte []的所有当前答案使我回到这段代码:

using (var ms = new MemoryStream(byte[])) 
{
  Bitmap bit = new Bitmap(ms);
}

至少是这样的(到目前为止,我已经制作了很多版本。我不记得原始版本了) 但是无论我如何使用它,当我尝试将流放入位图中时,总是得到该参数的“参数无效”。

这是我目前的保存方式:

private static byte[] ConvertToByteArr(Bitmap bitmap)
    {
        byte[] result;            
        MemoryStream stream = new MemoryStream();
        bitmap.Save(stream, ImageFormat.Bmp);            
        result = stream.ToArray();

        return result;
    }

并在将字典保存到.txt文件时调用它

这就是我尝试再次阅读的方式。

 TextReader reader = new StreamReader(trainingPath + "\\" + filename + ".txt");
        Dictionary<string, string> tempDict = new Dictionary<string, string>();
        String line;
        String[] parts;

        List<string> names = new List<string>();

        while ((line = reader.ReadLine()) != null)
        {
            parts = line.Split('=');

            string key = parts[0];
            string value = parts[1];
            tempDict.Add(key, value);

            Console.WriteLine("added " + key + " to temp Dict");

            byte[] byteArr = Encoding.ASCII.GetBytes(tempDict[key]);

            MemoryStream ms = new MemoryStream(byteArr);

            Bitmap bit = new Bitmap(Image.FromStream(ms));

            parts[0] = null;
            parts[1] = null;

        }

一切正常,直到位图位=新的位图(Image.Fromstream(ms))行为止。

2 个答案:

答案 0 :(得分:0)

不建议使用Encoding.GetBytes()和Encoding.GetString()。
有时上述相互转换无法顺利进行。
(就像您经历过的一样)

我建议使用十六进制字符串。
您可以按以下方式将字节数组转换为字符串(十六进制):

byte[] byteArr = ConvertToByteArr(bitmap);
string str = BitConverter.ToString(byteArr).Replace("-", "");


另外,您可以按如下所示将字符串(如上所述)转换为字节数组:

private byte[] HexaToBytes(string str)
{
    byte[] byteArr = new byte[str.Length / 2];
    for (int i = 0; i < byteArr.Length; i++)
    {
        string s = str.Substring(i * 2, 2);
        byteArr[i] = Convert.ToByte(s, 16);
    }
    return byteArr;
}

答案 1 :(得分:0)

从文本文件中读取时,请确保正在使用编码。 我尝试了一个示例代码,使用与上述提到的相同方法(ConvertToByteArr)将位图作为byte []保存到文本文件中。 当我尝试从该保存的文本文件的streamreader读取的memorystream中创建位图对象时,遇到了相同的错误。

但是当我使用ASCII编码时,效果很好。

TextReader reader = new StreamReader(textfile,Encoding.ASCII,true);

相关问题