将 BufferedImage 转换为 aws...rekognition.model.Image
Convert BufferedImage to aws...rekognition.model.Image
我正在使用 Amazon Rekognition。我找到了一个真正的 nice/easy library 来从我的网络摄像头拍摄图像,它的工作原理如下:
BufferedImage bufImg = webcam.getImage();
然后我尝试将此 BufferedImage
转换为 com.amazonaws.services.rekognition.model.Image
,这是必须提交给 Rekognition 库的内容。这就是我正在做的:
byte[] imgBytes = ((DataBufferByte) bufImg.getData().getDataBuffer()).getData();
ByteBuffer byteBuffer = ByteBuffer.wrap(imgBytes);
return new Image().withBytes(byteBuffer);
然而,当我尝试使用 Image
对 Rekognition 进行一些 API 调用时,我得到一个异常:
com.amazonaws.services.rekognition.model.InvalidImageFormatException: Invalid image encoding (Service: AmazonRekognition; Status Code: 400; Error Code: InvalidImageFormatException; Request ID: X)
docs 声明 Java SDK 将自动对字节进行 base64 编码。万一发生奇怪的事情,我尝试在转换之前对字节进行 base64 编码:
imgBytes = Base64.getEncoder().encode(imgBytes);
然而,同样的异常随之而来。
有什么想法吗? :)
我尝试将图像编码为 JPG(Rekognition 支持 PNG 或 JPG 格式)并解决了问题。
BufferedImage bufImg = webcam.getImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufImg, "jpg", baos);
ByteBuffer byteBuffer = ByteBuffer.wrap(baos.toByteArray());
return new Image().withBytes(byteBuffer);
我正在使用 Amazon Rekognition。我找到了一个真正的 nice/easy library 来从我的网络摄像头拍摄图像,它的工作原理如下:
BufferedImage bufImg = webcam.getImage();
然后我尝试将此 BufferedImage
转换为 com.amazonaws.services.rekognition.model.Image
,这是必须提交给 Rekognition 库的内容。这就是我正在做的:
byte[] imgBytes = ((DataBufferByte) bufImg.getData().getDataBuffer()).getData();
ByteBuffer byteBuffer = ByteBuffer.wrap(imgBytes);
return new Image().withBytes(byteBuffer);
然而,当我尝试使用 Image
对 Rekognition 进行一些 API 调用时,我得到一个异常:
com.amazonaws.services.rekognition.model.InvalidImageFormatException: Invalid image encoding (Service: AmazonRekognition; Status Code: 400; Error Code: InvalidImageFormatException; Request ID: X)
docs 声明 Java SDK 将自动对字节进行 base64 编码。万一发生奇怪的事情,我尝试在转换之前对字节进行 base64 编码:
imgBytes = Base64.getEncoder().encode(imgBytes);
然而,同样的异常随之而来。
有什么想法吗? :)
我尝试将图像编码为 JPG(Rekognition 支持 PNG 或 JPG 格式)并解决了问题。
BufferedImage bufImg = webcam.getImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufImg, "jpg", baos);
ByteBuffer byteBuffer = ByteBuffer.wrap(baos.toByteArray());
return new Image().withBytes(byteBuffer);