我正在用相机拍摄一些(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(...)“抛出如下错误:

保存方法的定义如下:
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,例如:
pictureBox1.Image = imageIn;
picturebox.Refresh();但是,既不能保存图像到MemoryStream,也不能保存到文件系统。
发布于 2016-05-31 18:38:36
试试这个-
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 ();
}
}https://stackoverflow.com/questions/37543136
复制相似问题