3

How can I convert a byte array from tiff image to a byte array of jpg?

I have the byte array of Tiff image from the web, then how can i use it as jpg without writing a new file?

roybalderama
  • 1,650
  • 21
  • 38

1 Answers1

5
Byte[] tiffBytes;
Byte[] jpegBytes;

using (MemoryStream inStream = new MemoryStream(tiffBytes))
using (MemoryStream outStream = new MemoryStream())
{
    System.Drawing.Bitmap.FromStream(inStream).Save(outStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    jpegBytes = outStream.ToArray();
}

I didn't try it but it should work. If you are going to save the file last you can just use the save method on the bitmap with a file path instead of a stream.

darin
  • 498
  • 3
  • 6
  • using (MemoryStream strm = new MemoryStream(startBytes)) System.Drawing.Bitmap.FromStream(strm).Save(localfileName, System.Drawing.Imaging.ImageFormat.Jpeg); To save to a file as jpeg. – darin Sep 20 '12 at 22:23
  • Would you mind explaining your code ? Will help the author understand your perspective quickly. – AYK Sep 21 '12 at 05:36
  • Would it not be better to use `outStream.ToArray()`? Or is there even a difference? – Samuel Parkinson Sep 21 '12 at 08:21
  • I don't know what the difference is. I always though the ToArray was converting an IEnumerable to an array and since a stream is not for the lack of a better explanation a List then I just used GetBuffer. As for the code you create a Bitmap from the MemoryStream created from you input Byte array. Then you use the Save Function of the Bitmap to save it to the output MemoryStream that you can then read the Byte Array out of. – darin Sep 21 '12 at 13:28
  • Searching the web I found you should use ToArray because it works when the stream is closed. Although in my example above they would both work since the stream would be out of scope outside the using statement. – darin Sep 21 '12 at 13:34