I'm working with the WPF imaging components in an attempt to do some simple image manipulation. I'm roughly following the MS article on How to Encode & Decode a JPEG Image.
My code is simple:
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("D:\\Temp\\StackOverflowCapture.png");
//bi.DecodePixelWidth = 1024;
//bi.DecodePixelHeight = 768;
bi.EndInit();
var jpg = new JpegBitmapEncoder();
jpg.QualityLevel = 90;
//jpg.FlipHorizontal = false;
//jpg.FlipVertical = false;
jpg.Frames.Add(BitmapFrame.Create(bi));
var fs = new FileStream("D:\\Temp\\StackOverflow_Result.jpg", FileMode.Create);
jpg.Save( fs );
jpg = null;
The code snippet creates an odd artifact, where the last few "lines" are a block of solid gray. It's almost as if the encoder just ran out of pixels to write. The amount of gray varies by a factor of 2x or 3x depending on the image I use as input (various resolutions, jpeg, png) or the options I enable (forcing resolution on decode). The net effect is the same, however, as you can see from the images below.
My source image is :
Output image ( note the gray band at the bottom):
What's going on here? How do I get a clean convert?
This was definitely a short circuit between the ears. For the sake of others with similar frailties, however, I'm answering my own question.
You need to close/flush the stream. Alternately, it would be good practice to create
fs
in ausing
block.Modified code is thus: