I am writing a program that gets an image encoded in base64 through the Serial port. I want to then load that image in my Processing program to analyze it.
It seems that loadImage() should work with base64 encoded data, provided you use the right header (reference), but even the gist used in the pull request throws a NullPointerException.
I have checked out the discussions i will post on a comment (this forum only lets new users post 2 links per post, for some reason) but nothing seems to work. I get either NullPointerException or IllegalArgumentException. Any help would be appreciated!
Here’s my code:
import processing.serial.*;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.Base64;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
processing.serial.Serial myPort;
String val;
PImage feed;
PrintWriter debug;
void setup(){
size(800, 800);
//print(Serial.list());
String portName = "COM3";
debug = createWriter("debug.txt");
myPort = new processing.serial.Serial(this, portName, 2000000);
}
void draw(){
background(0);
if(myPort.available() > 0){
val = myPort.readStringUntil('\n');
if(val != null){
println("_______________________");
debug.println(val.substring(873)); //Get rid of a bunch of characters prior to the base64 image
val = val.substring(val.indexOf("/"));
println(val.length());
if(val.startsWith("/")){
//This throws NullPointerException on image(feed, 0, 0)
//String data = "data:image/jpg;base64,"+val;
//feed = loadImage(data);
try {
feed = DecodePImageFromBase64(val);
}
catch (IOException e) {
println(e);
}
image(feed, 0, 0);
}
}
}
}
public PImage DecodePImageFromBase64(String i_Image64) throws IOException
{
PImage result = null;
byte[] decodedBytes = Base64.getDecoder().decode(i_Image64);
println("Base64");
ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);
BufferedImage bImageFromConvert = ImageIO.read(in);
BufferedImage convertedImg = new BufferedImage(bImageFromConvert.getWidth(), bImageFromConvert.getHeight(), BufferedImage.TYPE_INT_ARGB);
convertedImg.getGraphics().drawImage(bImageFromConvert, 0, 0, null);
result = new PImage(convertedImg);
return result;
}
void keyPressed() {
debug.flush(); // Writes the remaining data to the file
debug.close(); // Finishes the file
exit(); // Stops the program
}
I know I am getting the right serial data because I get it printed to a .txt file, and converting it with this tool gives me a valid image.
Using the code above, I get one of two errors:
- IllegalArgumentException: Input byte array has incorrect ending byte at 145536
- IllegalArgumentException: Input byte array has wrong 4-byte ending unit
I will also post an example of an encoded image.

