How can I save the canvas as Image, including the canvas child element.
I tried to save the canvas as image, but after the saving of the canvas. It's child element shown as elongated or streached. How can I stop to streach the canvas child element.
What I have tried:
<Canvas x:Name="MainObjectImage" Background="White" ClipToBounds="True"
SnapsToDevicePixels="True">
<Canvas x:Name="canvas_Draw" SnapsToDevicePixels="True">
<Image x:Name="imgSelectedImage" Canvas.Left="0" Canvas.Top="0" />
</Canvas>
<Image x:Name="imgForeGroundImage" Stretch="UniformToFill"
HorizontalAlignment="Stretch" />
</Canvas>
The following code I used for the save canvas as Image.
try
{
System.Windows.Size sizeOrignal = new System.Windows.Size(MainObjectImage.ActualWidth, MainObjectImage.ActualHeight);
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
double Width = 2160;
double Height = 1440;
if (MainObjectImage.Background != null)
{
ImageBrush Imbrush = (ImageBrush)MainObjectImage.Background;
if (Imbrush.ImageSource != null)
{
Width = Imbrush.ImageSource.Width;
Height = Imbrush.ImageSource.Height;
}
}
double sourceWidth = MainObjectImage.ActualWidth;
double sourceHeight = MainObjectImage.ActualHeight;
nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
int destWidth = (int)(sourceWidth * nPercentW);
int destHeight = (int)(sourceHeight * nPercentH);
FileStream fs = new FileStream(savedConvertedImage, FileMode.Create);
System.Windows.Size sizeRender = new System.Windows.Size(destWidth, destHeight);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(MainObjectImage.ActualWidth),
(int)(MainObjectImage.ActualHeight),
96,
96,
PixelFormats.Pbgra32);
Rect bounds = VisualTreeHelper.GetDescendantBounds(MainObjectImage);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(MainObjectImage);
ctx.DrawRectangle(vb, null, new Rect(new System.Windows.Point(), sizeRender));
}
rtb.Render(dv);
MemoryStream stream = new MemoryStream();
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
encoder.Save(fs);
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}