For starters, I\'m still new with UWP and XAML. I\'ve made a simple code on my uwp where I have a canvas (named it \"ImageHolder\") and there is an image and textblock inside it
It is due to your foreground is black you this is rendering black background, this will work --
FOR JPEG
XAML
<Canvas Name="ImageHolder" Height="260" Width="260">
<Canvas.Background>
<SolidColorBrush Color="White"/>
</Canvas.Background>
<Image x:Name="image" HorizontalAlignment="Left" Height="206" VerticalAlignment="Top" Width="226"/>
<TextBlock Text="Johnny!" Margin="44,89,-44,-89"></TextBlock>
</Canvas>
<Button x:Name="button" Background="Gray" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Top" Click="button_Click" />
i removed the button from canvas because you are using negative margin which is out of your canvas ant when you capture it or save it it renders dark black background so if you want button on it so place button inside the canvas
C#
private async void button_Click(object sender, RoutedEventArgs e)
{
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(ImageHolder);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
var displayInformation = DisplayInformation.GetForCurrentView();
var picker = new FileSavePicker();
picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
StorageFile file = await picker.PickSaveFileAsync();
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels);
await encoder.FlushAsync();
}
}
FOR PNG (Bonus)
XAML --> Your regular above XAML
because you will always get transparent background irrespective of any margin
private async void button_Click(object sender, RoutedEventArgs e)
{
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(ImageHolder);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
var displayInformation = DisplayInformation.GetForCurrentView();
var picker = new FileSavePicker();
picker.FileTypeChoices.Add("PNG Image", new string[] { ".png" });
StorageFile file = await picker.PickSaveFileAsync();
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels);
await encoder.FlushAsync();
}
}