【发布时间】:2012-04-02 18:27:06
【问题描述】:
我阅读了很多问题和答案,大多数建议:
byte[] byteArray; //(contains image data)
MemoryStream stream = new MemoryStream(byteArray);
Bitmap image = new Bitmap(stream);
pictureBox.Image = image;
或更直接地:
pictureBox.Image = Image.FromStream(stream);
我总是得到:“System.Drawing.dll 中发生了“System.ArgumentException”类型的未处理异常
附加信息:参数无效。"
关于流参数。
即使在以下情况下:
byte[] byteArray = new byte[1];
byteArray[0] = 255;
我不知道为什么。
编辑:
我从这样的文件中获取数据:
//byteArray is defined as List<byte> byteArray = new List<byte>();
TextReader tr = new StreamReader(file);
string File = tr.ReadToEnd();
string[] bits = File.Split('\t');
List<string> image = new List<string>(bits);
height = int.Parse(bits[0]);
width = int.Parse(bits[1]);
image.RemoveRange(0, 2);
image.RemoveAt(image.Count - 1);
foreach (string s in image)
{
byteArray.Add(byte.Parse(s));
}
return byteArray //(i do .ToArray() in the MemoryStream call);
在调试器中,我看到 byteArray 很好,count = 2244,值无处不在,等等。
编辑 #2:示例数据文件(第一个字节 [0] 是高度,第二个字节 [1] 是宽度,其余是 RGB 数据)
47 15 12 55 25 52 55 25 52 55 25 52 55 25 52 55
25 52 55 25 52 55 25 52 55 25 52 55 25 52 55 25
52 55 25 52 55 25 52 55 25 52 55 25 52 55 25 52
55 25 52 55 25 52 55 25 52 55 25 52 55 25 52 55
25 52 51 24 82 49 24 82 49 24 92 50 25 12 50 24
92 48 24 92 50 24 82 50 25 02 50 24 92 50 25 02
51 25 12 50 24 92 49 25 02 50 25 02 49 25 12 49
25 02 49 25 02 47 25 12 47 25 22 50 24 82 47 24
82 50 24 72 50 24 82 49 24 82 50 24 72 50 24 82
50 24 72 49 24 82 49 25 22 52 24 92 50 24 82 50
24 72 47 25 00 etc.
编辑#3:解决方案
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
IntPtr ptr = bmpData.Scan0;
Marshal.Copy(byteArray, 0, ptr, height * width * 3);
bmp.UnlockBits(bmpData);
pictureBox.Image = bmp;
需要检查4字节对齐,所以现在加载函数:
TextReader tr = new StreamReader(file);
string File = tr.ReadToEnd();
string[] bits = File.Split('\t');
List<string> image = new List<string>(bits);
height = int.Parse(bits[0]);
width = int.Parse(bits[1]);
int falseBits = 0;
int oldWidth = width;
while (width % 4 != 0)
{
width++;
falseBits++;
}
int size = height * width * 3;
byte[] byteArray = new byte[size];
Parallel.For(0, size - 1, i => byteArray[i] = 255);
int index = 0;
int lineIndex = 0;
image.RemoveRange(0, 2);
image.RemoveAt(image.Count - 1);
foreach (string s in image)
{
byteArray [index] = byte.Parse(s);
byteArray [index + 1] = byteArray [index];
byteArray [index + 2] = byteArray [index];
index +=3;
lineIndex++;
if (lineIndex == oldWidth)
{
lineIndex = 0;
index += 3*falseBits;
}
}
return byteArray ;
【问题讨论】:
-
bytearray中图片的格式是什么?最后一个例子永远不会工作......想不出一个字节的图像:)
-
那么 byte[] 数据格式不正确。
-
最后一个例子只是说即使我知道数据格式正确,如 leppie 所说,流也不起作用,我将编辑并编写我拥有的数据的示例
-
您能给我们看一个示例数据文件吗?
-
数据是否表示每个像素的实际 RGB 颜色值?一个像素使用多少字节?或者数据是否还包含标题(例如位图标题)?
标签: c# bitmap picturebox