简体   繁体   English

将字节数组转换为图像时,参数无效

[英]Parameter is not valid , while converting byte array to image

I want to save images in access database , I used OLE object . 我想在访问数据库中保存图像,我使用OLE对象。

The idea is to convert the image into bytes array , then adding the bytes array in the database. 我们的想法是将图像转换为字节数组,然后在数据库中添加bytes数组。

this is the function : 这是功能:

    public static byte[] ImageToByte(Image img)
    {
        ImageConverter converter = new ImageConverter();
        return (byte[])converter.ConvertTo(img, typeof(byte[]));
    }

this works fine . 这很好用。

When I want to return the bytes array to the image i get an exception : 当我想将bytes数组返回给图像时,我得到一个异常:

argument exception was unhandled Parameter is not valid. 参数异常未处理参数无效。

I tried two functions to convert the bytes array to the image : 我尝试了两个函数来将bytes数组转换为image:

    public static Image ImageFromByte(byte[] image)
    {
        ImageConverter ic = new ImageConverter();
        Image img = (Image)ic.ConvertFrom(image);//here the exception comes
        return img;
    }

OR: 要么:

    public static Image ImageFromByte1(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);//here the exception comes
        return returnImage;
    }

What is the problem , how to fix it ? 有什么问题,如何解决?

Try saving the image to disk, and see if that works. 尝试将图像保存到磁盘,看看是否有效。 Change the filename and extension as you see fit. 根据需要更改文件名和扩展名。

Something along these lines: 这些方面的东西:

            string path = @"c:\myimage.jpg";
            using (MemoryStream inputStream = new MemoryStream(byteArrayIn))
            {
                using (Stream file = File.Create(path))
                {
                    byte[] buffer = new byte[8 * 1024];
                    int len;
                    while ((len = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        file.Write(buffer, 0, len);
                    }
                } 
            }

EDIT: Writing image to disk works, and I guess you can see the image. 编辑:将图像写入磁盘工作,我想你可以看到图像。 Try this one: 试试这个:

            using (MemoryStream inputStream = new MemoryStream(byteArrayIn))
            {
                using (var image = Image.FromStream(inputStream))
                {
                    // see if this works.
                    // handle the image as you wish, return it, process it or something else.
                } 
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM