Why do I get completely different results when saving a BitmapSource to bmp, jpeg, and png in WPF

Posted by DanM on Stack Overflow See other posts from Stack Overflow or by DanM
Published on 2010-06-15T00:54:59Z Indexed on 2010/06/15 1:12 UTC
Read the original article Hit count: 464

Filed under:
|
|
|
|

I wrote a little utility class that saves BitmapSource objects to image files. The image files can be either bmp, jpeg, or png. Here is the code:

public class BitmapProcessor
{
    public void SaveAsBmp(BitmapSource bitmapSource, string path)
    {
        Save(bitmapSource, path, new BmpBitmapEncoder());
    }

    public void SaveAsJpg(BitmapSource bitmapSource, string path)
    {
        Save(bitmapSource, path, new JpegBitmapEncoder());
    }

    public void SaveAsPng(BitmapSource bitmapSource, string path)
    {
        Save(bitmapSource, path, new PngBitmapEncoder());
    }

    private void Save(BitmapSource bitmapSource, string path, BitmapEncoder encoder)
    {
        using (var stream = new FileStream(path, FileMode.Create))
        {
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.Save(stream);
        }
    }
}

Each of the three Save methods work, but I get unexpected results with bmp and jpeg. Png is the only format that produces an exact reproduction of what I see if I show the BitmapSource on screen using a WPF Image control.

Here are the results:


BMP - too dark

too dark


JPEG - too saturated

too saturated


PNG - correct

correct


Why am I getting completely different results for different file types?

I should note that the BitmapSource in my example uses an alpha value of 0.1 (which is why it appears very desaturated), but it should be possible to show the resulting colors in any image format. I know if I take a screen capture using something like HyperSnap, it will look correct regardless of what file type I save to.


Here's a HyperSnap screen capture saved as a bmp:

correct

As you can see, this isn't a problem, so there's definitely something strange about WPF's image encoders.

Do I have a setting wrong? Am I missing something?

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf