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

旧时模样 提交于 2019-12-28 06:27:31

问题


How can I convert a BITMAP in byte array format to JPEG format using .net 2.0?


回答1:


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);
    }



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/457370/c-how-to-convert-bitmap-byte-array-to-jpeg-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!