2

to give a background on what this topic is about. I am trying to convert an image file to byte[] by using a memorystream to return the memorystream.ToArray(); However, i have noticed that the image quality decreases after the conversion inputBitmap -> byte[] -> outputBitmap. outputBitmap has a lower quality than the inputBitmap. My code to convert the image to byte[] is as follows

MemoryStream mstream = new MemoryStream();
myImage.Save(mstream,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] buffer = mstream.ToArray();

and to convert from the byte[] back to an image,

MemoryStream mstream = new MemoryStream(buffer);
Image newImage = Image.FromStream(mstream);

can somebody explain why this is and hopefully guide me to correct this problem? Note that before i used the inputBitmap as my pictureBox.Image, it looks great in quality. But after converting from byte[] to outputBitmap, setting outputBitmap as my pictureBox.Image becomes kind of blurred and low in quality.

woodmon122
  • 45
  • 1
  • 5
  • Duplicate of http://stackoverflow.com/questions/1484759/quality-of-a-saved-jpg-in-c-sharp – Roy Dictus Jan 29 '13 at 11:32
  • @Roy Dictus: I am asking a question about quality loss after converting from a byte[]. Not saving an image. I have to convert it to a byte[] to be able to send it over my TcpClient to my listener – woodmon122 Jan 29 '13 at 11:40
  • Conversion to byte[] cannot cause any quality loss; it's the saving to JPEG that causes the quality loss. Conversion to byte[] is simply lossless transformation of data. – Roy Dictus Jan 29 '13 at 11:42

1 Answers1

5

A couple of things stand out for me.

  1. You are saving to JPG rather than a lossless format like PNG.
  2. You are not setting the quality of the compression used to save the image.

This means that you are probably compressing an image that has already been compressed thus losing even more information in the process.

I'd change to saving the file as PNG if I could, failing that make sure you set the quality of the JPG to 100% before you save it. This will reduce to a minimum the compression on the file and hence minimise the data loss.

If you're still seeing a difference in quality then the only thing that I can think of that might explain a this is a difference in the resolution (number of pixels and/or colour depth) between the screen shot and the saved file. Make sure you set the target bitmap size and colour depth to be the same as the source bitmap.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • There isn't really an original file format. i am using Graphics to take a screenshot(CopyFromScreen) to a bitmap – woodmon122 Jan 29 '13 at 11:50
  • @woodmon122 - Hmm. Then the only difference that might explain a "loss in quality" is a difference in the resolution (number of pixels) between the screen shot and the saved file. – ChrisF Jan 29 '13 at 11:56
  • Alright thank you Chris for your help. You've been a great help – woodmon122 Jan 29 '13 at 11:59