微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我想在访问数据库中保存图像,我使用OLE对象.

我们的想法是将图像转换为字节数组,然后在数据库添加bytes数组.

这是功能

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

这很好用.

当我想将bytes数组返回给图像时,我得到一个异常:

参数异常未得到处理
参数无效.

我尝试了两个函数来将bytes数组转换为image:

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

要么:

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

有什么问题,如何解决

解决方法

尝试将图像保存到磁盘,看看是否有效.根据需要更改文件名和扩展名.

这些方面的东西:

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,buffer.Length)) > 0)
                    {
                        file.Write(buffer,len);
                    }
                } 
            }

编辑:将图像写入磁盘工作,我想你可以看到图像.试试这个:

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.
                } 
            }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐