从数据URI解码QR码

时间:2016-01-20 10:55:14

标签: javascript qr-code data-uri

我尝试从数据uri中解码qr代码:

var dataUri = 'data:image/gif;base64,R0lGODdh9gD2AIAAAAAAAP///ywAAAAA9gD2AAAC...';
decodeQrCode(dataUri, cb);

我已尝试qrcode-decoder-jsexample with mocha test

function decodeQrCode(dataUri, cb) {
  qrcode.callback = cb;
  qrcode.decode(dataUri);
}
// error decoding QR Code

qcode-decoderexample with mocha test

function decodeQrCode(dataUri, cb) {
  var qr = new QCodeDecoder();
  var img = document.createElement('img');
  img.setAttribute('src', dataUri);
  qr.decodeFromImage(img, cb);
}
// Error decoding QR Code from Image

但在我看来,两者都不支持数据URI。

如何从数据URI中解码QR码?

1 个答案:

答案 0 :(得分:6)

您遇到的错误是您的QR码方向不正确。

旋转90度后的结果如下:

window.onload = function() {
  var img = document.querySelector('img');
  var canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext('2d');
  // rotate by 90 deg
  ctx.rotate(Math.PI);
  ctx.translate(-img.width, -img.height);
  ctx.drawImage(img, 0, 0);
  // decode
  QCodeDecoder().decodeFromImage(canvas.toDataURL(), function(err, res){
    document.body.appendChild(document.createTextNode(res||err))
    });
  
}
*{vertical-align : top}
<script src="https://rawgit.com/cirocosta/qcode-decoder/master/build/qcode-decoder.min.js"></script>
<img id="qr-code" src="data:image/gif;base64,R0lGODdh9gD2AIAAAAAAAP///ywAAAAA9gD2AAAC/4SPqcsaDx2cs9mLZU006B5lCEiGViem6sqO1Ee2coNyr116ax5f9QwMqn4Hnk4IJBqUACPLyIQdkdRq8ebKWWXMLu8J3Zyw23KSvPyah+hm27kLm2jttT3j1d7x776eLTfFELUnFdiTNTfop7gANyaWcggiZcj4YDkZuahZUulzKeioBtmI0bnplvp4tYqKSPeaZ4rTSJgIy0lb2vmJS1mLGSwrzEssettqWzecnJZ6KuurnKu6fLxLfTytW6wd/Reb3a3JbV09iw2Ojcz8a545fi663jsc7/18zV5PD+o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