Hi, this is my first English post, well my first English translate post.

You know some time ago I had the need to add some information to an image so I was looking at MSDN and found the RenderTargetBitMap class, this class allows us to get images from XAML controls, this is especially useful when we want to generate thumbnail or to share a picture of these controls with other applications. RenderTargetBitmap allows us to generate these images through its RenderAsync method.

Consider a simple example in which we will add additional data to an image obtained by the camera. Like a first step we will create a user interface that will allow us to connect to the camera, it will display the image and add the date and the time.


After we have done this we will add two buttons to the user interface, the first to take a picture and the second to save the resulting image, for this we will use the first button click event and add the following code.

private async void btnTakePhoto_Click(object sender, RoutedEventArgs e) 
CameraCaptureUI cameraUi = new CameraCaptureUI(); cameraUi.PhotoSettings.AllowCropping = false; cameraUi.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.MediumXga; 
Windows.Storage.StorageFile capturedMedia = await cameraUi.CaptureFileAsync(CameraCaptureUIMode.Photo); 

using (var streamCamera = await capturedMedia.OpenAsync(FileAccessMode.Read)) 
BitmapImage bitmapCamera = new BitmapImage(); bitmapCamera.SetSource(streamCamera); imgSource.Source = bitmapCamera; txtDate.Text = DateTime.Now.ToString("D"); 

In the second button, we will add the following code that will allow us to create our image after our controls to later save them.

private async void btnSave_Click(object sender, RoutedEventArgs e) 
 FileSavePicker picker = new FileSavePicker(); 
picker.FileTypeChoices.Add("JPG File", new List<string>() { ".jpg" });
 StorageFile file = await picker.PickSaveFileAsync(); if (file != null) 
RenderTargetBitmap renderTargetBitMap = new RenderTargetBitmap(); 
//With this method we can make our XAML elements in an image. await renderTargetBitMap.RenderAsync(grdRender, (int)grdRender.Width, (int)grdRender.Height); var pixels = await renderTargetBitMap.GetPixelsAsync(); 

using (IRandomAccessStream randomAccessStream = await file.OpenAsync(FileAccessMode.ReadWrite))
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, randomAccessStream); 
byte[] bytes = pixels.ToArray(); 
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitMap.PixelWidth, (uint)renderTargetBitMap.PixelHeight, 96, 96, bytes); await encoder.FlushAsync(); 

With this, we get the following result and quite simply we will have achieved our goal.


The solution, as usual, I leave on GitHub, I hope you find useful, see you in the nest post, greeting!