Search code examples
c#system.drawing.imaging

Get RTF Image Html base64 string as System.Drawing.Image


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.


Solution

  • 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.