This code works to load a png file and make a base64 string, but I want to go directly from a pgraphics pixels[] array to a base64 string.
public static String encoder(String imagePath) {
String base64Image = "";
File file = new File(imagePath);
try {
FileInputStream imageInFile = new FileInputStream(file);
// Reading a Image file from file system
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
base64Image = Base64.getEncoder().encodeToString(imageData);
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return base64Image;
}
This is my attempt but it doesn’t make usable base64… it’s too long and doesn’t look right or work. It’s full of “/r”
void pgToBase64(PGraphics pg){
pg.loadPixels();
ByteBuffer byteBuffer = ByteBuffer.allocate(pg.pixels.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(pg.pixels);
String encoded = Base64.getEncoder().encodeToString(byteBuffer.array());
println(encoded);
}
edit: just realized I’m skipping the step where I convert from bytes to png. still not sure how to do it though…