How to save an image in it's original format?
- by Patrick Klug
I am trying to figure out how I can get the original format of an image so that I can store it with the same encoding.
It seems that the only way to save an Image is by using a BitmapEncoder but I don't know how I can get the correct format from the image.
Example:
Clipboard.GetImage() returns a InteropBitmap which doesn't seem to contain any information about the original format.
I also tried using an Extension method:
public static void Save(this BitmapImage image, System.IO.Stream stream)
{
var decoder = BitmapDecoder.Create(image.StreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat);
foreach (var frame in decoder.Frames)
{
encoder.Frames.Add(BitmapFrame.Create(decoder.Frames[0]));
}
encoder.Save(stream);
}
but the problem is that a) the ImageSource is not always a BitmapImage (Clipboard.GetImage()) for example and b) the image.StreamSource can be null in some cases (seems to be when the image is loaded via a relative Uri)