【发布时间】:2016-05-31 10:26:35
【问题描述】:
我正在用相机拍摄一些(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 个元素)。它没有什么特别之处。
你们知道为什么会发生这种情况吗?
感谢您的宝贵时间。
编辑:
我可以将图像设置为图片框,例如:
pictureBox1.Image = imageIn;
picturebox.Refresh();
但是,图像既不能保存到 MemoryStream 也不能保存到文件系统。
【问题讨论】:
-
你确定 imageIn 有 System.Drawing.Imaging.ImageFormat.Jpeg 格式吗?
-
尝试先转换成Bitmap再保存到MemoryStream
-
是的,我确定它是 JPEG 格式的。我在“if (ImageFormat.Jpeg.Equals(clonedImage.RawFormat))”处对此进行了检查。而且,亲爱的 JericCruz,我被要求以 jpeg 格式插入它们,因此我没有更改它的奢侈。
-
它更像是 hack,但我是从 Image 的来源获得的。如果格式为 JPEG,请尝试使用 ImageFormat.Png (internal void Save(MemoryStream stream))
-
请尝试创建minimal reproducible example,最好是你使用的真实图片文件,有很多不相关的代码。
标签: c# bytearray jpeg memorystream