Search code examples
c#mauisyncfusionimagesourcesignaturepad

How to get Base64 string from ImageSource?


I'm trying to get a Base64 string from an ImageSource object in C# MAUI .NET 7.0. I'm using SyncFusion Signature Pad component with ToImageSource();

I can't understand how to use this ImageSource and convert it to a base64 string.

I tried also to save the ImageSource into a View.Image as Source and then use View.SaveAsImage() but I'm getting file not found error when I try use the file.

References:

My code attempt:

private void btnConfermaClicked(object sender, EventArgs e)
    {
        Log.Verbose("Signature confirm clicked");

        ImageSource source_firma = signaturePad.ToImageSource();
        Log.Debug($"Signature as {source_firma.GetType()}");

        immagine.Source = source_firma;

        // Generate random file name
        string fileName = Path.GetRandomFileName() + ".png";

        string folderName = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        string path = Path.Combine(folderName, fileName);
        Log.Debug($"Random path: {path}");

        Log.Verbose("Start saving image");
        try
        {
            immagine.SaveAsImage(path);
        } catch (Exception ex)
        {
            Log.Error($"Error while saving image: {ex.Message}");
        }
        Log.Verbose("Done saving image");

        byte[] bytes = File.ReadAllBytes(path);
        string base64 = Convert.ToBase64String(bytes);
        Log.Debug($"Signature base64: {base64}");
    } 

And this is the log output:

[0:] [19:15:49 VRB] Signature confirm clicked
[0:] [19:15:49 DBG] Signature as Microsoft.Maui.Controls.StreamImageSource
[0:] [19:15:49 DBG] Random path: /data/user/0/com.companyname.iglogestorepresenze/files/eaiktmuj.0gr.png
[0:] [19:15:49 VRB] Start saving image
[gestorepresenz] Explicit concurrent copying GC freed 12995(775KB) AllocSpace objects, 7(5008KB) LOS objects, 84% free, 4446KB/28MB, paused 32us total 14.729ms
[0:] [19:15:49 VRB] Done saving image
**System.IO.FileNotFoundException:** 'Could not find file '/data/user/0/com.companyname.iglogestorepresenze/files/eaiktmuj.0gr.png'.'

Edit:

  • immagine is a view Image. In XAML: <Image id="immagine" />

Solution

  • I finally discovered how to convert my image source into a base64 encoded string.
    I managed to do this without saving the image in a file.
    This is what I've done:

    private void btnConfermaClicked(object sender, EventArgs e)
        {
    
            Log.Verbose("Signature confirm clicked");
    
            StreamImageSource source_firma = (StreamImageSource)signaturePad.ToImageSource();
    
            if (source_firma == null)
            {
                Log.Error("Signature not available");
                return;
            }
    
            System.Threading.CancellationToken cancellationToken = System.Threading.CancellationToken.None;
            Task<Stream> task_stream = source_firma.Stream(cancellationToken);
            Stream stream = task_stream.Result;
    
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
    
            string base64 = "data:image/jpg;base64," + Convert.ToBase64String(bytes);
            Log.Debug($"Signature base64: {base64}");
    
        }