Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exception when converting base64 image to byte array

I have a base64 string that looks like this:

data:image/png;base64,iVBORw0KGgoA….

And I need to convert the string to an image as byte array so I do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var b = Convert.FromBase64String(base64string);

But I get an exception:

System.FormatException: ‘The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

What am I doing wrong?

>Solution :

You didn’t remove the "data:image/png;base64," part of the string which contains redundant text helpful for browsers to recognize it as image. You can remove it using following code:

var text = "insert your text here";
var header = "base64,";
var startpos = text.IndexOf(header) + header.Length;
var decode = Convert.FromBase64String(text[startpos..]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading