Working in WPF and C#, I have a TransformedBitmap object that I either 1) Need to save to disk as a bitmap type of file (ideally, I'll allow users to choose whether it's saved as a BMP, JPG, TIF, etc, though, I'm not to that stage yet...), or 2) Need to convert to a BitmapImage object as I know how to get a byte[] from a BitmapImage object. Unfortunately, at this point I'm really struggling to get either one of those two things done. Can anyone offer any help or point out any methods I might be missing? Thanks a lot!
+1
A:
All of your encoders are using BitmapFrame
class for creating frames that will be added to Frames
collection property of encoder. BitmapFrame.Create
method has variety of overloads and one of them accepts parameter of BitmapSource
type. So as we know that TransformedBitmap
inherits from BitmapSource
we can pass it as a parameter to BitmapFrame.Create
method. Here are the methods which works as you have described:
public bool WriteTransformedBitmapToFile<T>(BitmapSource bitmapSource, string fileName) where T : BitmapEncoder, new()
{
if (string.IsNullOrEmpty(fileName) || bitmapSource == null)
return false;
//creating frame and putting it to Frames collection of selected encoder
var frame = BitmapFrame.Create(bitmapSource);
var encoder = new T();
encoder.Frames.Add(frame);
try
{
using (var fs = new FileStream(fileName, FileMode.Create))
{
encoder.Save(fs);
}
}
catch (Exception e)
{
return false;
}
return true;
}
private BitmapImage GetBitmapImage<T>(BitmapSource bitmapSource) where T : BitmapEncoder, new()
{
var frame = BitmapFrame.Create(bitmapSource);
var encoder = new T();
encoder.Frames.Add(frame);
var bitmapImage = new BitmapImage();
bool isCreated;
try
{
using (var ms = new MemoryStream())
{
encoder.Save(ms);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();
isCreated = true;
}
}
catch
{
isCreated = false;
}
return isCreated ? bitmapImage : null;
}
They accept any BitmapSource as the first parameter and any BitmapEncoder as a generic type parameter.
Hope this helps.
Eugene Cheverda
2010-09-07 14:13:38
Wow, very much so! I didn't really know how the different encoders worked (or how to apply them). Thanks a ton!
JToland
2010-09-07 15:20:08