Parse Image Text as an Image

If I have an image as a raw string, how can I parse it to be viewed as an image? As an example, can read in this picture of a cat, but say I have it as text, not as an image. How can I get it to be viewed as an image from this state, going from the text to a rendered image?

Notebook

Always learning,
Zach

If you can get the PNG as base64 encoded, then you could do something like this:

<img src="${imgText}"/>

I just tried this in your notebook and it worked (taken from SO):

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

Thanks for the timely response! I’m afraid I don’t understand what that SO post is doing. That long string is a base64 encoding of some kind? How would I specify the big PNG string I have as the source?

Can you avoid the raw string and get an array buffer or some other binary representation instead? Why is it that you have only a raw string or text?

True, it’s coming from an API, so I could use use an arrayBuffer to get at the data instead? Is going from arrayBuffer to an image have an easy solution?

1 Like

If you are using Fetch, you can say

imageBlob = FileAttachment("604px-Siamese_cat_on_white_towels.png").blob()
<img src=${URL.createObjectURL(imageBlob)}>

If you have an ArrayBuffer for some reason, you can get a data URL like so:

imageUrl = new Promise((resolve) => {
  const blob = new Blob([imageBuffer], {type: "image/png"});
  const reader = new FileReader();
  reader.onload = (event) => resolve(reader.result);
  reader.readAsDataURL(blob);
})
<img src=${imageUrl}>
1 Like

Great, that is working, thanks!