AWS Rekognition JS SDK无效的图像编码错误

时间:2017-04-25 00:15:22

标签: reactjs amazon-web-services amazon-rekognition

使用<input type="file">

使用React构建简单的AWS Rekognition演示

出现Invalid image encoding错误。

let file = e.target.files[0];
let reader = new FileReader();

reader.readAsDataURL(file);

reader.onloadend = () => {
  let rekognition = new aws.Rekognition();

  var params = {
    Image: { /* required */
      Bytes: reader.result,
    },
    MaxLabels: 0,
    MinConfidence: 0.0
  };

  rekognition.detectLabels(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
  });

enter image description here

GitHub回购:https://github.com/html5cat/vision-test/

GitHub问题:https://github.com/html5cat/vision-test/issues/1

3 个答案:

答案 0 :(得分:3)

您可以尝试将reader.result转换为二进制字节。

function getBinary(encodedFile) {
        var base64Image = encodedFile.split("data:image/jpeg;base64,")[1];
        var binaryImg = atob(base64Image);
        var length = binaryImg.length;
        var ab = new ArrayBuffer(length);
        var ua = new Uint8Array(ab);
        for (var i = 0; i < length; i++) {
          ua[i] = binaryImg.charCodeAt(i);
        }

        var blob = new Blob([ab], {
          type: "image/jpeg"
        });

        return ab;
      }

您实际上可以为字节设置上述方法的响应:

 Bytes: getBinary(reader.result),

答案 1 :(得分:2)

如果有人在Node端执行此操作,我在作为字节数组缓冲区读取文件并将其发送到Rekognition时遇到了类似的问题。

我通过读取base64表示来解决它,然后将其转换为这样的缓冲区:

const aws = require('aws-sdk');
const fs = require('fs');

var rekognition = new aws.Rekognition({
  apiVersion: '2016-06-27'
});

// pull base64 representation of image from file system (or somewhere else)
fs.readFile('./test.jpg', 'base64', (err, data) => {

  // create a new base64 buffer out of the string passed to us by fs.readFile()
  const buffer = new Buffer(data, 'base64');

  // now that we have things in the right type, send it to rekognition
  rekognition.detectLabels({
      Image: {
        Bytes: buffer
      }
    }).promise()
    .then((res) => {

      // print out the labels that rekognition sent back
      console.log(res);

    });

});

这可能与获得Expected params.Image.Bytes to be a string, Buffer, Stream, Blob, or typed array object消息的人有关。

答案 2 :(得分:0)

ReadAsDataUrl的返回值包括一个前缀,表示数据的MIME-TYPE和编码。 (&#34; image / png; base64, IVBORsdafasdfasf ...&#34;)。

但是,Rekognition API只需要图像的编码字节,而不需要任何前缀。

尝试reader.result.split(',')[1]过滤掉前缀并仅传递请求中的编码字节。