C#:如何将 BITMAP 字节数组转换为 JPEG 格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/457370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: How to convert BITMAP byte array to JPEG format?
提问by Marc
How can I convert a BITMAP in byte array format to JPEG format using .net 2.0?
如何使用 .net 2.0 将字节数组格式的 BITMAP 转换为 JPEG 格式?
采纳答案by Marc Gravell
What type of byte[]
do you mean? The raw file-stream data? In which case, how about something like (using System.Drawing.dll
in a client application):
byte[]
你指的是什么类型?原始文件流数据?在这种情况下,例如(System.Drawing.dll
在客户端应用程序中使用)如何:
using(Image img = Image.FromFile("foo.bmp"))
{
img.Save("foo.jpg", ImageFormat.Jpeg);
}
Or use FromStream
with a new MemoryStream(arr)
if you really do have a byte[]
:
或者FromStream
,new MemoryStream(arr)
如果您确实有一个,请与 a 一起使用byte[]
:
byte[] raw = ...todo // File.ReadAllBytes("foo.bmp");
using(Image img = Image.FromStream(new MemoryStream(raw)))
{
img.Save("foo.jpg", ImageFormat.Jpeg);
}
回答by baretta
If it is just a buffer of raw pixel data, and not a complete image file(including headers etc., such as a JPEG) then you can't use Image.FromStream.
如果它只是原始像素数据的缓冲区,而不是完整的图像文件(包括标题等,例如 JPEG),则不能使用 Image.FromStream。
I think what you might be looking for is System.Drawing.Bitmap.LockBits, returning a System.Drawing.Imaging.ImageData; this provides access to reading and writing the image's pixels using a pointer to memory.
我想你可能正在寻找的是 System.Drawing.Bitmap.LockBits,返回一个 System.Drawing.Imaging.ImageData; 这提供了使用指向内存的指针读取和写入图像像素的访问。
回答by juanjo.arana
public static Bitmap BytesToBitmap(byte[] byteArray)
{
using (MemoryStream ms = new MemoryStream(byteArray))
{
Bitmap img = (Bitmap)Image.FromStream(ms);
return img;
}
}