Image.FromStream()方法返回无效参数异常 [英] Image.FromStream() method returns Invalid Argument exception
问题描述
我从一个智能摄像头成像仪捕捉图像,并通过套接字编程接收来自摄像头的字节数组(.NET应用程序是客户端,摄像头是服务器)。
I am capturing images from a smart camera imager and receiving the byte array from the camera through socket programming (.NET application is the client, camera is the server).
现在的问题是,我得到在运行时System.InvalidArgument例外。
The problem is that i get System.InvalidArgument exception at runtime.
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{
MemoryStream ms = new MemoryStream(byteArray);
return Image.FromStream(ms, false, false);
/*last argument is supposed to turn Image data validation off*/
}
return null;
}
我寻觅在许多论坛这个问题,并试图通过许多专家给出的建议,但没有任何帮助。
I have searched this problem in many forums and tried the suggestions given by many experts but nothing helped.
我不认为有与字节数组作为这样的任何问题,因为当我喂相同的字节数组我用VC ++ MFC客户端应用程序,我得到的图像。但是,这并不以某种方式在C#.NET工作。
I dont think there is any problem with the byte array as such because When i feed the same byte array into my VC++ MFC client application, i get the image. But this doesn't somehow work in C#.NET.
谁能帮我?
P.S:
其他方法我试过来完成相同的任务是:
Other methods i've tried to accomplish the same task are:
1。
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{
MemoryStream ms = new MemoryStream();
ms.Write(byteArray, 0, byteArray.Length);
ms.Position = 0;
return Image.FromStream(ms, false, false);
}
return null;
}
2。
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap b = (Bitmap)tc.ConvertFrom(byteArray);
return b;
}
return null;
}
无上述方法的工作。请帮助。
None of the above methods worked. Kindly help.
推荐答案
Image.FromStream()
预计只包含一个图像流!
Image.FromStream()
expects a stream that contains ONLY one image!
它重置stream.Position为0。我已经有一个包含多个图片或其他的东西流,你必须阅读的图像数据转换成字节数组,初始化的MemoryStream 与
It resets the stream.Position to 0. I've you have a stream that contains multiple images or other stuff, you have to read your image data into a byte array and to initialize a MemoryStream with that:
Image.FromStream(新的MemoryStream(myImageByteArray));
在的MemoryStream 必须保持打开状态,只要图像中使用。
The MemoryStream has to remain open as long as the image is in use.
我lerned了艰辛的道路了。 :)
I've lerned that the hard way too. :)
这篇关于Image.FromStream()方法返回无效参数异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!