Skip to content

Instantly share code, notes, and snippets.

@shiffman
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save shiffman/392dd647c8e2595772e9 to your computer and use it in GitHub Desktop.

Select an option

Save shiffman/392dd647c8e2595772e9 to your computer and use it in GitHub Desktop.
PImage encoded to Base64 String
// This is for Java 7
// With Java 8 you can now say:
import javax.xml.bind.DatatypeConverter;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
// Load an image
PImage img = loadImage("file.jpg");
// Funky steps to convert to byte array
ByteBuffer byteBuffer = ByteBuffer.allocate(img.pixels.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(img.pixels);
byte[] imgBytes = byteBuffer.array();
// Or maybe just better to load as bytes?
// byte[] imgBytes = loadBytes("file.png");
// Now make it a base 64 String
// Java 7
String base64String = DatatypeConverter.printBase64Binary(imgBytes);
// Java 8
// String base64String = Base64.getEncoder().encodeToString(imgBytes);
println(base64String);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment