MVC Convert Base64 String to image, but ... System.FormatException

My controller receives the uploaded image in the request object in this code:

[HttpPost] public string Upload() { string fileName = Request.Form["FileName"]; string description = Request.Form["Description"]; string image = Request.Form["Image"]; return fileName; } 

The value of the image (at least the beginning of it) looks something like this:

 data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/... 

I tried to convert using the following:

 byte[] bImage = Convert.FromBase64String(image); 

However, this gives a System.FormatException: "Input is not a valid Base-64 string because it contains a non-base 64 character, more than two padding characters, or an invalid character among padding characters."

I get the feeling that the problem is that at least the beginning of the line is not base64, but for everyone I know, it is not. Do I need to parse a string before decrypting it? Did I miss something completely different?

+6
source share
2 answers

It looks like you can just remove the "data:image/jpeg;base64," from the beginning. For instance:

 const string ExpectedImagePrefix = "data:image/jpeg;base64,"; ... if (image.StartsWith(ExpectedImagePrefix)) { string base64 = image.Substring(ExpectedImagePrefix.Length); byte[] data = Convert.FromBase64String(base64); // Use the data } else { // Not in the expected format } 

Of course, you can do this a little less than JPEG, but I would try this as the very first pass.

+9
source

The reason really is "data: image / jpeg; base64", I suggest using this method to remove the starting line from base64

 var base64Content = image.Split(',')[1]; byte[] bImage = Convert.FromBase64String(base64Content); 

This is the shortest solution, and you do not need to use magic lines or write a regular expression.

+5
source

All Articles