convert byte[] of jp2 to jpg file

10.4k Views Asked by At

I have a byte array of jp2, how can I convert that to JPG file? Thank you

Thank all the answers. I made some differences and nearly succeeded. Here is how I do it:

using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        String id = (String)reader["ID"];
                        blob = (byte[])reader["Data"];

                        using (MemoryStream ms = new MemoryStream(blob))
                        {
                            FIBITMAP dib = FreeImage.LoadFromStream(ms);                            
                            if (dib.IsNull)
                            {
                                continue;
                            }                           
                            string jpgName = getJpgName(id);
                            FreeImage.Save(FREE_IMAGE_FORMAT.FIF_JPEG, dib, jpgName, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL);
                        }
                    }
                }

I read byte[] from database. Now another problem arises; there exists memory leak! Could someone pick it out?

2

There are 2 best solutions below

11
On BEST ANSWER

We don't have anything built in .Net to do this but, You can use FreeImage which is a free library that can do this.

Here is an Example on doing this.

FIBITMAP dib = FreeImage.LoadEx("test.jp2");
//save the image out to disk    
FreeImage.Save(FREE_IMAGE_FORMAT.FIF_JPEG, dib, "test.jpg", FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL);
//or even turn it into a normal Bitmap for later use
Bitmap bitmap = FreeImage.GetBitmap(dib);

For converting from a stream of bytes u can try this:

byte[] myByte = new byte[10];
MemoryStream theMemStream = new MemoryStream();
theMemStream.Write(myByte, 0, myByte.Length);
FreeImageBitmap fbm = FreeImageBitmap.FromStream(theMemStream);
fbm.Save("text.jpg",FREE_IMAGE_STREAM.FIF_JPEG);
0
On

Download FreeImageAPI from nuget package. Add the reference of FreeImageAPI.dll in your project. Check your package folder in that you will have FreeImage.dll, keep that dll in project bin folder. Download FreeImageAPI from nuget package. Add the reference of FreeImageAPI.dll in your project. Check your package folder in that you will have FreeImage.dll, keep that dll in project bin folder.

    public ActionResult FileUpload(HttpPostedFileBase file)
    {
      Stream str =  file.InputStream;
      MemoryStream theMemStream = new MemoryStream();
      FIBITMAP dib = FreeImage.LoadFromStream(str);
      FreeImage.SaveToStream(dib,theMemStream,FREE_IMAGE_FORMAT.FIF_JPEG);
      return RedirectToAction("Index", theMemStream);
    }

Change theMemStream to byte[], base64string etc.