PImage to base64

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…

I don’t have a straight up solution, but one thing to note is that you are putting the entire pixels array, but nowhere in your encoded string you are storing the actual height or width of the image!

I think it would make sense to allocate 8 more bytes right before the actual data, and then put width integer into first 4 and height integer into second 4 - and only then follow up with the data.

Then, you could make a base64ToPg(String input) function(that you are skipping) that takes these first 8 bytes into account to do createGraphics(decodedWidth,decodedHeight), then loadPixels() on it, then load it with the rest of the data, savePixels(), done, hooray. :v

Is this useful? EncodePImageToBase64 uses Apache Commons Base64.

import org.apache.commons.codec.binary.Base64;
public String EncodePImageToBase64(PImage i_Image) throws UnsupportedEncodingException, IOException {
    String result = null;
    BufferedImage buffImage = (BufferedImage)i_Image.getNative();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(buffImage, "PNG", out);
    byte[] bytes = out.toByteArray();
    result = Base64.encodeBase64URLSafeString(bytes);
    return result;
}

This also might be relevant: “Upload an image to image hoster Imgur (can be used for PGraphics, too)”