Last active
August 29, 2015 14:10
-
-
Save shiffman/392dd647c8e2595772e9 to your computer and use it in GitHub Desktop.
PImage encoded to Base64 String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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