Do you remove the data:image/jpeg;base64, before decoding Base64 string using C#?

I'm trying to convert a Base64 encoded string that was generated from a re-sized image from the canvas element and I'm getting the following error when converting using the Convert.FromBase64()

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.

The encoded data looks like this to start and ends with the =

data:image/jpeg;base64,/...=

What I don't quite understand is when I perform the Convert.FromBase64() do I need to strip off the prefix of data:image/jpeg;base64, and then decode the remainder?

The code I'm using to decode this is like below

string base64String = newinput.Value.ToString();

// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);


// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);

string newFile = Guid.NewGuid().ToString() + ".jpg";
image.Save(Path.Combine(Server.MapPath("~/Assets/") + Request.QueryString["id"] + "/", newFile), ImageFormat.Jpeg);

Basically, I'm converted the string into the image and saving on the server. As you can see I'm using C#

Any ideas?

Jon Skeet
people
quotationmark

do I need to strip off the prefix of data:image/jpeg;base64, and then decode the remainder?

Yes - the prefix isn't base64-encoded text, it's just saying that the rest is base64-encoded (and what the mime-type is).

We don't know exactly how you're obtaining the data, but you should check that the data URL is claiming to be base64 encoded first, mind.

people

See more on this question at Stackoverflow