简体   繁体   中英

C#: How to convert BITMAP byte array to JPEG format?

如何使用.net 2.0将字节数组格式的BITMAP转换为JPEG格式?

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):

    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[] :

    byte[] raw = ...todo // File.ReadAllBytes("foo.bmp");
    using(Image img = Image.FromStream(new MemoryStream(raw)))
    {
        img.Save("foo.jpg", ImageFormat.Jpeg);
    }

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.

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.

public static Bitmap BytesToBitmap(byte[] byteArray)
{
  using (MemoryStream ms = new MemoryStream(byteArray))
  {
    Bitmap img = (Bitmap)Image.FromStream(ms);
    return img;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM