1

I have a base64 jpeg like so: data:image/jpeg;base64 and I am trying to convert it to a MemoryStream so I can upload it to OneDrive....Here is what I got so far:

byte[] frontBytes = Convert.FromBase64String(user.FrontLicense);

using (MemoryStream frontMS = new MemoryStream(frontBytes))
{
    await graphClient.Me.Drive.Items[newFolder.Id].ItemWithPath("FrontLicense.jpeg").Content.Request().PutAsync<DriveItem>(frontMS);
}

But I get this error:

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.

On this line:

byte[] frontBytes = Convert.FromBase64String(user.FrontLicense);

This is what user.FrontLicense looks like:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoM.....

What am I doing wrong?

user979331
  • 11,039
  • 73
  • 223
  • 418
  • You need to remove the `data:image/jpeg;base64,` before base64-decoding it. –  Nov 18 '19 at 16:21
  • Looks like this might be a duplicate... [check out this question](https://stackoverflow.com/questions/15114044/the-input-is-not-a-valid-base-64-string-as-it-contains-a-non-base-64-character) – JEllery Nov 18 '19 at 16:21
  • 2
    @JEllery: Not a duplicate of that. – Jon Skeet Nov 18 '19 at 16:23

1 Answers1

4

The part at the start - data:image/jpeg;base64, - isn't part of the base64 data. So you need to remove that first:

const string Base64ImagePrefix = "data:image/jpeg;base64,"
...

if (user.FrontLicense.StartsWith(Base64ImagePrefix))
{
    string base64 = user.FromLicense.Substring(Base64ImagePrefix.Length);
    byte[] data = Convert.FromBase64String(base64);
    // Use the data
}
else
{
    // It didn't advertise itself as a base64 data image. What do you want to do?
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194