C#:当我尝试将System.Drawing.Image保存到MemoryStream时抛出错误

时间:2016-05-31 10:26:36

标签: c# bytearray jpeg memorystream

我正在用相机拍摄一些(jpeg)图像并将它们插入数据库(作为blob)。为了将它们插入数据库,我必须以字节数组的形式传递图像。

这是一个转换为字节数组的小代码:

public static byte[] JpegToByteArray(System.Drawing.Image imageIn)
    {                        
       MemoryStream ms = new MemoryStream();
       imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); //PROBLEM IS HERE!
       return  ms.ToArray();
    }

虽然,我确信我传递的图像是jpeg格式,“imageIn.Save(...)”会抛出错误,如下所示:

enter image description here

以下是保存方法的定义:

    public void Save(Stream stream, ImageFormat format);
    //
    // Summary:
    //     Saves this System.Drawing.Image to the specified file in the specified format.
    //
    // Parameters:
    //   filename:
    //     A string that contains the name of the file to which to save this System.Drawing.Image.
    //
    //   format:
    //     The System.Drawing.Imaging.ImageFormat for this System.Drawing.Image.
    //
    // Exceptions:
    //   System.ArgumentNullException:
    //     filename or format is null.
    //
    //   System.Runtime.InteropServices.ExternalException:
    //     The image was saved with the wrong image format.-or- The image was saved
    //     to the same file it was created from.

我检索并传递给函数的图像永远不会存储到文件系统/从文件系统读取。将图像插入数据库后,我将其处理掉。我检索图像的方法只返回System.Drawing.Image列表(包含4个元素)。没什么特别的。

你们有没有想过为什么会这样?

感谢您的时间。

编辑:

我可以将图像设置到图片框,例如:

pictureBox1.Image = imageIn;
picturebox.Refresh();

但是,无法将图像既不保存到MemoryStream也不保存到文件系统。

1 个答案:

答案 0 :(得分:-2)

试试这个 -

priority_queue

来源 - How to save image in database using C#