Use loadimage() with base64-encoded PNG.

Hello everyone,

I am trying to load an image from a base64-encoded string with loadImage like this: loadimage(“data:image/png;base64,iVBORw0KGgoA…”), but it is not working (I cut the base64 string short in this post for space). When I this, I get an error saying, “The file “data:image/png;base64,iVBOR…” is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable.”

I know the encoded string is valid, and as far as I am aware, it is possible to do this. Does anyone know how I can solve this?

Thank you

Is this for Processing(Java) or p5.js?

Where did you find this use of data: urls with loadImage documented or demonstrated?

This is for Java. I was mistaken. That said, I was easily able to implement a base64 PImage loader by extending the PApplet class, so the problem has been solved.

Glad to hear that you were able to solve your problem!

If you are extending PApplet then am I right that you are working in eg Eclipse? Some forum members might be interested in the encoder method if you are willing to share it.

Yes, I am indeed working in Eclipse. As for my code, I would be glad to share it. Here it is!

import java.awt.Image;
import java.awt.Toolkit;
import java.util.Base64;

import processing.core.PImage;

public class PAppletExt extends processing.core.PApplet {
	private static final long serialVersionUID = 1L; // This is here to suppress an Eclipse warning.
	
	public PImage loadBase64PNG(String base64Str) {
		// Loads a PImage from a given base 64-encoded PNG image given as a string.
		byte[] imageBytes = Base64.getDecoder().decode(base64Str);
		Image awtImage = Toolkit.getDefaultToolkit().createImage(imageBytes);
		return super.loadImageMT(awtImage);
	}
}
2 Likes

I added a pull request for base64 image support