首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#:尝试将System.Drawing.Image保存到MemoryStream时引发错误

C#:尝试将System.Drawing.Image保存到MemoryStream时引发错误
EN

Stack Overflow用户
提问于 2016-05-31 18:26:36
回答 1查看 661关注 0票数 1

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

下面是执行字节数组转换的一小段代码:

代码语言:javascript
复制
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(...)“抛出如下错误:

保存方法的定义如下:

代码语言:javascript
复制
    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个元素)。它没有什么特别之处。

你们知道为什么会发生这种事吗?

耽误您时间,实在对不起。

编辑:

我可以将图像设置为picturebox,例如:

代码语言:javascript
复制
pictureBox1.Image = imageIn;
picturebox.Refresh();

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

EN

回答 1

Stack Overflow用户

发布于 2016-05-31 18:38:36

试试这个-

代码语言:javascript
复制
    public static void PerisitImage(string path, IDbConnection connection)
{
    using (var command = connection.CreateCommand ())
    {
        Image img = Image.FromFile (path);
        MemoryStream tmpStream = new MemoryStream();
        img.Save (tmpStream, ImageFormat.Png); // change to other format
        tmpStream.Seek (0, SeekOrigin.Begin);
        byte[] imgBytes = new byte[MAX_IMG_SIZE];
        tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);

        command.CommandText = "INSERT INTO images(payload) VALUES (:payload)";
        IDataParameter par = command.CreateParameter();
        par.ParameterName = "payload";
        par.DbType = DbType.Binary;
        par.Value = imgBytes;
        command.Parameters.Add(par);
        command.ExecuteNonQuery ();
    }
}

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

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37543136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档