Converting a JPEG image to a byte array - COM exception(将 JPEG 图像转换为字节数组 - COM 异常)
问题描述
使用 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 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 JPEG 图像转换为字节数组 - COM 异常
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
