Base64String to ImageSource throws an unhandled exception

Viewed 66

I'm trying to load an image by a given base 64 string.

I have the following XAML Image:

<Image x:Name="CustomImage"></Image>

And I have this method on the class page, whose is called after InitializeComponent() in the constructor:

public void LoadImage(string imageString)
{
    CustomImage.Source = ImageSource.FromStream(() =>
    {
        return imageString.StringToStream();
    });
}

The extension method called:

public static Stream StringToStream(this string image)
{
     var imageBytes = Convert.FromBase64String(image);
     using (var ms = new MemoryStream())
     {
         ms.Write(imageBytes, 0, imageBytes.Length);
         return ms;
     }
}

No exception is thrown by the method, but an unhandled exception is thrown after the code is executed.

What I am doing wrong? I can't catch the exception, because is thrown outside my code.

3 Answers

Try below Code :

CustomImage.Source = ImageSource.FromStream(
                () => new MemoryStream(Convert.FromBase64String(imageString)));

Probably the error is that the cursor's position is at the end of the stream.

You can correct it changing your code to be like this:

The LoadImage method:

public void LoadImage(string imageString)
{
    CustomImage.Source = ImageSource.FromStream(() => imageString.StringToStream());
}

The Extension method:

public static Stream StringToStream(this string image)
{
     var imageBytes = Convert.FromBase64String(image);
     return new MemoryStream(imageBytes);
}

Try the following:

CustomImage.Source = ImageSource.FromStream(() => new MemoryStream(System.Convert.FromBase64String(imageString)));
Related