25

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

Marc
  • 9,012
  • 13
  • 57
  • 72

3 Answers3

44

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);
    }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • The second one was just what I was searching for. I'm however writing into another MemoryStream rather than to file. Thanks! – Marc Jan 19 '09 at 14:22
4

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.

baretta
  • 7,385
  • 1
  • 25
  • 25
-4
public static Bitmap BytesToBitmap(byte[] byteArray)
{
  using (MemoryStream ms = new MemoryStream(byteArray))
  {
    Bitmap img = (Bitmap)Image.FromStream(ms);
    return img;
  }
}
jdearana
  • 1,089
  • 12
  • 17
  • this is a bitmap. he wants a jpeg. – AnthonyBlake Apr 12 '12 at 13:53
  • Correct, the code is not complete. But it returns a Bitmap, which you can later on save to a file in any format.... I guess this is my welcome to the Reputation Wars... My fault anyway. – jdearana Mar 11 '14 at 11:14
  • @juanjo.arana but you have not given an answer to his question, just told him how to get a bitmap. – gbjbaanb Apr 01 '14 at 12:54