Xamarin SignaturePad Image conversion to and from Base64

The following code shows how to convert a PNG image (Stream) to a Base64 string, and back from a Base64 string to a Stream and into an ImageSource. The example uses SignaturePad (https://github.com/xamarin/SignaturePad), since we needed to convert the resulting signature and store it in a database, and also display it on a website. The resulting Base64 string is only ~40KB, but that size is dependent on the size of input you implement in your app.

In XAML, we added the element:

<ContentPage xmlns:controls="clr-namespace:SignaturePad.Forms;assembly=SignaturePad.Forms" ... >
     <controls:SignaturePadView x:Name="the_signature" StrokeWidth="3" StrokeColor="Black" BackgroundColor="White" HeightRequest="80"></controls:SignaturePadView>

In the following example, the Xamarin SignaturePad element is named “the_signature”, which is of type SignaturePadView, and we will convert the generated PNG to a base64 string:

private async Task Signature()
     // convert png image to base64
     System.IO.Stream signature_image = await the_signature.GetImageStreamAsync(SignaturePad.Forms.SignatureImageFormat.Png);
     byte[] bytes = new byte[signature_image.Length];
     signature_image.Position = 0;
     signature_image.Read(bytes, 0, (int)signature_image.Length);
     string signature = Convert.ToBase64String(bytes);

To convert it back from base64 and load it into an ImageSource:

byte[] bytes = Convert.FromBase64String(signature);
System.IO.Stream stream = new System.IO.MemoryStream(bytes);
ImageSource the_signature_image = ImageSource.FromStream(() => stream);

Now we can apply “ImageSource the_signature_image” to the SignaturePadView element:

the_signature.Source = the_signature_image;

Leave a Reply

Your email address will not be published.