Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Get jpeg encoded in base64 string into Mat in Java.

I am trying to do a simple face detection example in Java, similar to what was done in the Introduction to Java Development article. When I load a jpeg image using Highgui.imread(path), everything works fine. But the images I am using come from an API that returns base64 encoded jpegs. My code for handling the base64 strings looks like this:

CascadeClassifier classifier = new CascadeClassifier(getClass().getResource("/lbpcascade_frontalface.xml").getPath());

// img is a String
byte[] bytes = parseBase64Binary(img); // This function is found in javax.xml.bind.DatatypeConverter
Mat image = new Mat;
image.put(0, 0, bytes);
MatOfRect faceDetections = new MatOfRect();
classifier.detectMultiScale(image, faceDetections);

This does not work. I tested it by encoding an image in which a face was successfully detected when loaded directly:

DataBufferByte byteBuffer = (DataBufferByte) ImageIO.read(new File(path_to_file_that_worked_before)).getRaster.getDataBuffer();
String img = printBase64Binary(byteBuffer.getData);

No faces are detected. Any idea what I am doing wrong?