本文介绍了将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:
我认为该文件没有什么特别之处 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?
推荐答案
查看本文中的例子:
此外,最好使用中的类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异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!