JpegBitmapEncoder leaves gray streak at end of fil

2019-03-06 15:50发布

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 :

enter image description here

Output image ( note the gray band at the bottom):

enter image description here

What's going on here? How do I get a clean convert?

1条回答
趁早两清
2楼-- · 2019-03-06 16:44

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 a using block.

Modified code is thus:

BitmapImage bi = new BitmapImage();

bi.BeginInit();
bi.UriSource = new Uri("D:\\Temp\\StackOverflow_Source.png");
bi.EndInit();

var jpg                  = new JpegBitmapEncoder();
    jpg.QualityLevel     = 90;
    jpg.Frames.Add(BitmapFrame.Create(bi));

var fs = new FileStream("D:\\Temp\\StackOverflow_Result.jpg", FileMode.Create);

jpg.Save( fs );
fs.close();       <--- duh, flush the stream to disk
jpg = null;
查看更多
登录 后发表回答