问题描述
使用 C#,我正在尝试从磁盘加载 JPEG 文件并将其转换为字节数组.到目前为止,我有这个代码:
Using C#, I'm trying to load a JPEG file from disk and convert it to a byte array. So far, I have this code:
static void Main(string[] args)
{
System.Windows.Media.Imaging.BitmapFrame bitmapFrame;
using (var fs = new System.IO.FileStream(@"C:Lenna.jpg", FileMode.Open))
{
bitmapFrame = BitmapFrame.Create(fs);
}
System.Windows.Media.Imaging.BitmapEncoder encoder =
new System.Windows.Media.Imaging.JpegBitmapEncoder();
encoder.Frames.Add(bitmapFrame);
byte[] myBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
encoder.Save(memoryStream); // Line ARGH
// mission accomplished if myBytes is populated
myBytes = memoryStream.ToArray();
}
}
但是,执行 ARGH
行给了我消息:
However, executing line ARGH
gives me the message:
COMException 未处理.句柄无效.(例外来自HRESULT: 0x80070006 (E_HANDLE))
COMException was unhandled. The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))
我认为文件 Lenna.jpg
没有什么特别之处 - 我是从 http://computervision.wikia.com/wiki/File:Lenna.jpg.你能说出上面的代码有什么问题吗?
I don't think there is anything special about the file Lenna.jpg
- I downloaded it from http://computervision.wikia.com/wiki/File:Lenna.jpg. Can you tell what is wrong with the above code?
推荐答案
查看本文中的示例:http://www.codeproject.com/KB/recipes/ImageConverter.aspx
另外,最好使用 System.Drawing
Image img = Image.FromFile(@"C:Lenna.jpg");
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
arr = ms.ToArray();
}
这篇关于将 JPEG 图像转换为字节数组 - COM 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!