将 JPEG 图像转换为字节数组 - COM 异常
使用 C#,我尝试从磁盘加载 JPEG 文件并将其转换为字节数组。到目前为止,我有这段代码:
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
行会给出以下消息:
COMException 未处理。句柄无效。 (例外情况来自 HRESULT:0x80070006(E_HANDLE))
我认为文件 Lenna.jpg
没有什么特别之处 - 我从 http://computervision.wikia.com/wiki/File:Lenna.jpg。你能看出上面的代码有什么问题吗?
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();
}
}
However, executing line ARGH
gives me the message:
COMException was unhandled. The handle is invalid. (Exception from
HRESULT: 0x80070006 (E_HANDLE))
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查看本文中的示例:http://www.codeproject.com/KB/recipes/ ImageConverter.aspx
此外,最好使用
System.Drawing
中的类Check the examples from this article: http://www.codeproject.com/KB/recipes/ImageConverter.aspx
Also it's better to use classes from
System.Drawing
其他建议:
不应该只处理图像。
Other suggestion:
Should be working not only with images.
发生此错误的原因是您使用的 BitmapFrame.Create() 方法默认为 OnDemand 加载。 BitmapFrame 不会尝试读取与其关联的流,直到调用encoder.Save,此时流已被释放。
您可以将整个函数包装在 using {} 块中,或者使用替代的 BitmapFrame.Create(),例如:
The reason this error happens is because the BitmapFrame.Create() method you are using defaults to an OnDemand load. The BitmapFrame doesn't try to read the stream it's associated with until the call to encoder.Save, by which point the stream is already disposed.
You could either wrap the entire function in the using {} block, or use an alternative BitmapFrame.Create(), such as: