2015-08-11 5 views
2

Моя цель:Зачем создавать холст, отображающий пустой файл изображения?

Если кнопка камеры на моем сайте щелкают> открыть смартфон камеры> взять изображение с QR-кода> изменить его с JS> загрузить изображение на моем сервере> читать QR-код > дайте мне значение из qr-кода обратно.

Моя проблема заключается в том, что мой код создает пустой файл изображения (jpg) и дает мне ошибку.

Я тестировал его с загрузкой существующего изображения qr-кода, и он работает во второй попытке загрузить его. С первой попытки я получаю такую ​​же ошибку, как если бы я попытался загрузить снимок с смартфона.

мой HTML

<form id="qr-code-upload-form" class="form-group" action="" method="post" enctype="multipart/form-data"> 
    <label> 
     <span id="qr-pic" class="glyphicon glyphicon-camera"></span> 
     <input type="file" capture="camera" accept="image/*" id="cameraInput" name="cameraInput" style="display: none;"> 
    </label> 
    <canvas id="cnvsForFormat" width="400" height="266" style="display:none;"></canvas> 
</form> 

мой JS/JQuery

$(document).ready(function(){ 
    $('body').on("change", "#cameraInput", readCode); 

    function readCode() { 
     var cnvs=document.getElementById("cnvsForFormat"); 
     var input = document.getElementById('cameraInput').files[0]; 
     var img = new Image(); 
     if (input) { 
      var reader = new FileReader(); 
      reader.onload = function (e) { 
       //Get the input image file 

       img.src = e.target.result; 

       var newHeight = img.height/2; 
       var newWidth = img.width/2; 

       //reduce the size until its lower than 600px 
       while (newWidth>600 || newHeight>600) { 
        newHeight = newHeight/2; 
        newWidth = newWidth/2; 
       } 
       $("#cnvsForFormat").attr("height",newHeight); 
       $("#cnvsForFormat").attr("width",newWidth); 

       //Draw the input image in a canvas with the right size for the upload 
       var ctx=cnvs.getContext("2d"); 
       ctx.drawImage(img,0,0, newWidth, newHeight); 
       var resizedImg = cnvs.toDataURL("image/jpeg"); 

       //Send the resized Image to my php-request-file 
       $.post("?cmd=ajax&param=qr_verarbeiten",{photo:resizedImg},function(e) { 
        alert(e); 
       }); 
      }; 
      reader.readAsDataURL(input); 
     } 
    }; 
}); 
</script> 

мой PHP, чтобы прочитать QR-код

if (isset($_GET['param']) && $_GET['param'] == "qr_verarbeiten" && isset($_POST['photo'])) { 

$img = base64_decode(substr($_POST['photo'],23)); 

file_put_contents("img/upload/qr.jpg", $img); 
$qrcode = new QrReader("img/upload/qr.jpg"); 
echo $qrcode->text(); 
} 

Я использую JQuery, Bootstrap и Smarty в этом проекте

Я действительно h кто-нибудь может мне помочь!

Спасибо, что нашли время, чтобы прочитать это, и я приношу свои извинения за мой плохой английский.

Проблема была в js. И я добавил JS/MegaPixImage Libraray обрабатывать большие файлы я получаю от камеры iPhone - Рабочий код:

$(document).ready(function(){ 
    $('body').on("change", "#cameraInput", readCode); 

    function readCode() { 
     // var cnvs=document.getElementById("cnvsForFormat"); 
     var input = document.getElementById('cameraInput').files[0]; 
     if (input) { 
      var img = new Image(); 
      var reader = new FileReader(); 
      reader.onload = function (e) { 
       img.onload = function() { 

        var count=0; 
        while (img.width<1) { 
         count++; 
        } 

        var newHeight = img.height; 
        var newWidth = img.width; 

        while (newWidth>600 || newHeight>600) { 
         newHeight = newHeight/2; 
         newWidth = newWidth/2; 
        } 

        var renderImg = new Image(); 
        var mpImg = new MegaPixImage(img); 
        mpImg.render(renderImg, { width: newWidth, height: newHeight }); 

        $.post("?cmd=ajax&param=qr_verarbeiten",{photo:renderImg.src},function(e) { 
         alert(e); 
        }); 
       }; 
       img.src = e.target.result; 
      }; 
      reader.readAsDataURL(input); 
     } 
    }; 
}); 

ответ

0

Я получил его. Это было причиной того, что браузер загружает asynchron img.src. Поэтому я должен добавить функцию img.onload, прежде чем загружать свой img.src, чтобы убедиться, что img уже отображается. ;-)

Я добавил рабочий код к моему вопросу.

Смежные вопросы