0

I am storing a Rich Text html string in our database, examples as follows (I have shortened the bit info):

data:image/png;base64,iVBORw0...ORK5CYII
data:image/jpeg;base64,/9j/4AAQS...TcUQrQf/Z

I need to basically take this HTML and create a System.Drawing.Image in C# and then save the image to a location within the Images folder. With the first png example above this all seemed to work fine with the following code:

        string imageBase64String = "iVBORw0...ORK5CYII";

        byte[] bytes = Convert.FromBase64String(imageBase64String);
        Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            image = Image.FromStream(ms);
        }

        string fileNameFull = Guid.NewGuid().ToString() + "." + imageFormat;
        string relativePath = @"~\Images\pdfExports\" + fileNameFull;
        string fileLocation = HttpContext.Current.Server.MapPath(relativePath);
        image.Save(fileLocation);

However when I try other formats including jpg/jpeg it seems like the image is not being created correctly and cannot be read/opened.

Is there a better, more generic way of getting C# System.Drawing.Image from this Html String? Or am I just missing something simple with how the base64 string is passed?

EDIT I was late up posting this and missed out some vital info on the code example where I am stripping out the meta data. I have updated now. By the time the string imageBase64String is populated I have already stripped out the meta.

CJH
  • 1,266
  • 2
  • 27
  • 61

2 Answers2

1

You are corrupting the image's data, data:image/png;base64, is metainformation, not real image content, you must remove that information before converting the data to binary:

string imageBase64String = "data:image/png;base64,iVBORw0...ORK5CYII";

int index = imageBase64String.IndexOf(",");
imageBase64String  = imageBase64String .Substring(index + 1);

byte[] bytes = Convert.FromBase64String(imageBase64String);
Gusman
  • 14,905
  • 2
  • 34
  • 50
  • Hi Gusman, thanks for the response. I have made an edit on the code above as I have mistakingly shown the wrong string being passed. I have in fact stripped out the meta data from the string - despite what my example previously said. Sorry. As I mentioned, this seems to work fine with PNG files but not jpeg/jpg. – CJH Mar 19 '18 at 09:35
0

I have managed to get this working fine with a simple change. Instead of trying to create a System.Drawing.Image object from the byte-array and saving that, i have found using:

File.WriteAllBytes(fileLocation, bytes);

does the job simply passing the original bytes and a file location. Now I seem to be able to save and open any image format I need.

CJH
  • 1,266
  • 2
  • 27
  • 61