Embedding images in a Python script with base64

I have a script that has images required for the UI, and I was wondering if it was possible to embed the images in the script, instead of having to save them somewhere on the hard drive. So I googled it, and came across something called base64. I can extract a string of characters from an image, but I can’t figure out where it goes from there.

Does anyone have experience with embedding small images in a Python script (so that there are no dependant files required)?

Thanks,

Dan

Hi @DanBayn,

Does this help?

import System
import os

def test():
    bytes = System.Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
    with System.IO.MemoryStream(bytes) as ms:
        image = System.Drawing.Image.FromStream(ms)
        desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
        path = os.path.join(desktop, 'test.png')
        image.Save(path)

test()

– Dale

2 Likes

Hi @dale,

Very helpful, thanks.

Dan

Hi @dale,

I’m having some trouble opening my saved image, and I suspect it’s because of the delay in saving the image to the hard drive. There is about a 1/2 second delay. I was wondering if there is a way to save the image to memory instead of an actual save to see if it’s more instantaneous.

Thanks,

Dan

Hi @DanBayn,

That is the intended use of the bitmap?

– Dale

Hi @dale

What I’m trying to do is attach an image to a script I have, without relying on images saved somewhere on the hard drive. Like this:

image

It works very well with the images pre-saved, but I’m just trying to push the envelope (my envelope anyway) to see if I can do this without having dependent files. Your example was very helpful in creating the images “on the fly” but I can’t load the images when I select the various radio buttons. I notice that the images take about 1/2 a second to show up in explorer so I’m thinking this delay might be causing the issue. Here is a short video where you can see the delay.

I don’t even know if this is possible, so if you don’t think it is, just let me know and I will abandon this project and stick with the dependent images.

Thanks,

Dan

1 Like

Hi @DanBayn

At this point, you have a bitmap in memory. Is this all you need?

– Dale

Ah, so I’ve taken farther than I needed to. Okay, I’ll see what I can do with this insight.

Thanks Dale,

Dan