Convert BufferedImage to aws...rekognition.model.Image

954 views Asked by At

I'm playing around with the Amazon Rekognition. I found a really nice/easy library to take an image from my webcam which works like this:

BufferedImage bufImg = webcam.getImage();

I'm then trying to convert this BufferedImage to a com.amazonaws.services.rekognition.model.Image , which is what must be submitted to the Rekognition library. This is what I'm doing:

byte[] imgBytes = ((DataBufferByte) bufImg.getData().getDataBuffer()).getData();
ByteBuffer byteBuffer = ByteBuffer.wrap(imgBytes);
return new Image().withBytes(byteBuffer);

However when I try and do some API call to Rekognition with the Image, I get an Exception:

com.amazonaws.services.rekognition.model.InvalidImageFormatException: Invalid image encoding (Service: AmazonRekognition; Status Code: 400; Error Code: InvalidImageFormatException; Request ID: X)

The docs state that the Java SDK will automatically base64 encode the bytes. In case, something weird was happening, I tried base64 encoding the bytes before converting:

imgBytes = Base64.getEncoder().encode(imgBytes);

However, the same Exception ensues.

Any ideas? :)

1

There are 1 answers

0
mickzer On BEST ANSWER

I tried encoding the image to a JPG (Rekognition supports PNG or JPG formats) and it solved the problem.

BufferedImage bufImg = webcam.getImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufImg, "jpg", baos);
ByteBuffer byteBuffer = ByteBuffer.wrap(baos.toByteArray());
return new Image().withBytes(byteBuffer);