[英]C#: error is thrown when I try to save System.Drawing.Image to a MemoryStream
I am taking some (jpeg) images with a camera and inserting them to the database (as a blob). 我正在用相机拍摄一些(jpeg)图像,并将它们插入数据库(作为Blob)。 In order to insert them to the database, I have to pass the image in a byte array.
为了将它们插入数据库,我必须将图像传递到字节数组中。
Here is a little code that does the conversion to the byte array: 这是一些转换为字节数组的代码:
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();
}
Although, I am sure that the image I pass is in jpeg format, "imageIn.Save(...)" throws an error as follows: 虽然,我确定传递的图像是jpeg格式,但“ imageIn.Save(...)”会引发如下错误:
Here is the definition of saving method: 这是保存方法的定义:
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.
The image(s) I retrieve and pass to the function are never stored to/read from the file system. 我检索并传递给函数的图像从不存储到文件系统或从文件系统读取。 After I insert the image to the database, I dispose it.
将图像插入数据库后,将其处置。 And the method that I retrieve images just returns a list of System.Drawing.Image (with 4 elements).
我检索图像的方法仅返回System.Drawing.Image的列表(包含4个元素)。 There is nothing special about it.
没什么特别的。
Do you guys have any idea why this might happen? 你们知道为什么会发生这种情况吗?
Thanks for your time. 谢谢你的时间。
EDIT: 编辑:
I am able to set the images to the picturebox, for example: 我可以将图像设置到图片框,例如:
pictureBox1.Image = imageIn;
picturebox.Refresh();
But, cannot save the images neither to MemoryStream, nor to the file system. 但是,不能将图像既不保存到MemoryStream,也不保存到文件系统。
Try this- 尝试这个-
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 ();
}
}
Source- How to save image in database using C# 来源- 如何使用C#在数据库中保存图像
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.