You could use RenderTargetBitmap class and BitmapEncoder.
Define these methods:
void SaveToBmp(FrameworkElement visual, string fileName)
{
var encoder = new BmpBitmapEncoder();
SaveUsingEncoder(visual, fileName, encoder);
}
void SaveToPng(FrameworkElement visual, string fileName)
{
var encoder = new PngBitmapEncoder();
SaveUsingEncoder(visual, fileName, encoder);
}
// and so on for other encoders (if you want)
void SaveUsingEncoder(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
BitmapFrame frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (var stream = File.Create(fileName))
{
encoder.Save(stream);
}
}
If you have your Image control inside a container like this:
<Grid x:Name="MyGrid">
<Image Name="MyImage" Stretch="None"></Image>
</Grid>
You just need to do so:
SaveToPng(MyGrid, "image.png");
Otherwise you can simply pass the dimensions you want when you use RenderTargetBitmap:
SaveToPng(MyImage, "image.png");
...
RenderTargetBitmap bitmap = new RenderTargetBitmap(YourWidth, YourHeight, 96, 96, PixelFormats.Pbgra32);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…