本文介绍了Image.FromStream() 方法返回 Invalid Argument 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从智能相机成像器捕获图像并通过套接字编程从相机接收字节数组(.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.

有人可以帮我吗?

附:

我尝试完成相同任务的其他方法是:

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(new MemoryStream(myImageByteArray));

只要图像在使用中,MemoryStream 就必须保持打开状态.

The MemoryStream has to remain open as long as the image is in use.

我也通过艰难的方式了解到这一点.

I've learned that the hard way, too.

这篇关于Image.FromStream() 方法返回 Invalid Argument 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 04:32