Loading images from base64 encoded strings

So, I'm trying to display images in a report that are encoded in a database as base64 encoded strings.

I've tried a couple of options, neither of which work. I just get a blank picture and no errors;

Both of these options were placed into the _BeforePrint handler.
// Just use image location as per a couple of stack overflow answers
picture.ImageLocation = (string)Report.GetColumnValue("Data.image");

// Load the image into an Image object and assign that to the image property.
Image i; 
byte[] image = Convert.FromBase64String((string)Report.GetColumnValue("Data.image"));
using (var ms = new MemoryStream(image, 0, image.Length)){
    i = Image.FromStream(ms, true);
}
picture.Image = i;

Anyone have any ideas? This has been asked before, and I found an example in the forum, but the example file is no longer available. And since the question was quite old I didn't want to necro it.


Thanks,
L.

Comments

  • edited May 2019
    Ok, never mind. After a lot of trial and error, it turns out this was not working because I still had the DataColumn property set on the image. This does not appear to be overridden, unlike other controls such as text (such as when you TextControl.Text = "some text").
  • Hello!

    The cleanest and most cross-platform way to set a Base64-decoded image in the BeforePrint event (after clearing the DataColumn) is to use SetImageData(byte[]) instead of ImageLocation and Image.FromStream:

    private void Picture1_BeforePrint(object sender, EventArgs e)
    {
    var pic = (PictureObject)sender;
    string b64 = Convert.ToString(Report.GetColumnValue(“Imgs.B64”));
    if (!string.IsNullOrEmpty(b64))
    pic.SetImageData(Convert.FromBase64String(b64));
    }
    
This discussion has been closed.