2017-04-25 24 views
1

构建一个简单的AWS Rekognition演示与反应,运用<input type="file">AWS Rekognition JS SDK无效的图像编码错误

获得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

回答

2

您可以尝试将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), 
+0

工作。谢谢! –

+0

非常感谢! –

0

从ReadAsDataUrl返回值包含一个前缀指示数据的MIME类型和编码。 (“image/png; base64, IVBORsdafasdfasf ...”)。

但是,Rekognition API仅预期图像的编码字节,没有任何前缀。

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

+0

似乎也没有工作。 –

0

如果有人这样做,在节点侧,读入文件时,我也陷入了类似的问题作为一个字节数组缓冲区并发送给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消息。