I have this layout:
<StackPanel>
<Button x:Name="button" Content="Button" Click="button_Click" Height="50" />
<Image x:Name="image" Source="vermelho.jpg" />
</StackPanel>
The code I tested to write the image to a png file is as follows:
private void button_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "imagem";
dlg.DefaultExt = ".png";
dlg.Filter = "Imagem PNG (.png)|*.png";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
var encoder = new PngBitmapEncoder();
SaveUsingEncoder(image, dlg.FileName, encoder);
}
}
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);
}
}
Why is it that when I open the image recorded on the disc, the area corresponding to the button is also saved in transparent?