簡體   English   中英

php上傳之前使用FileReader調整多個圖像的大小

[英]Multiple image resize with FileReader before php upload

我在php中有一個可以正常工作的多上傳腳本(還有一點javascript)。 問題在於,用戶直接從相機拍攝照片,因此圖像尺寸很大,而移動帶寬很小。

因此,我搜索了一種解決方案,以調整圖像客戶端的大小,並找到了一些與FileReader和canvas相關的帖子。

我的問題是如何使用我的php上傳腳本上傳filereader的“結果”。

那就是我所擁有的:

HTML:

<input id="fileupload" type="file" name="images[]" multiple/>

動態添加上傳字段和預覽上傳的Javascript:

var abc = 0; 
$(document).ready(function() {
$('#add-file-field').click(function() {
 $("#newrow").append("<div class='col-sm-4'><div id='newrow' class='card'><div class='card-body'><input id='fileupload' type='file' name='images[]' multiple/></div></div></div>");
});

$('body').on('change', '#fileupload', function(){
  if (this.files && this.files[0]) {
       abc += 1; 

      var z = abc - 1;
      var x = $(this).parent().find('#previewimg' + z).remove();
      $(this).before("<div id='abcd"+ abc +"' class='card-img-top abcd'><img id='previewimg" + abc + "' src='' style='width:100%; height:100%;'/></div>");

      var reader = new FileReader();
      reader.onload = imageIsLoaded;
      reader.readAsDataURL(this.files[0]);

      $(this).hide();

      $("#abcd"+ abc).append($("<img/>", {id: 'delete', src: 'x.png', alt: 'delete'}).click(function() {
      $(this).parent().parent().parent().remove();
      }));
  }
});
//To preview image     
function imageIsLoaded(e) {
      $('#previewimg' + abc).attr('src', e.target.result);
  };
  $('#upload').click(function(e) {
  var name = $(":file").val();
  if (!name)
  {
      alert("First Image Must Be Selected");
      e.preventDefault();
  }
  });
});   

和Php腳本:

$lastpositionid = $_SESSION['lastpositionid'];
$query = "INSERT INTO media (posid,orderid,name,image,created,tag,type) VALUES('$lastpositionid',$position->order_id,?,?,'$date','Vorher',?)";
$stmt = $con->prepare($query);

if(isset($_FILES['images'])){

        $countfiles = count($_FILES['images']['name']);
        $target_directory = "../uploads/". $position->order_id;

        $file_upload_error_messages="";

        for($i=0;$i<$countfiles;$i++){

            if(!is_dir($target_directory)){
               mkdir($target_directory, 0777, true);
            }

            $filename = $_FILES['images']['name'][$i];
            $shafilename = sha1_file($_FILES['images']['tmp_name'][$i]) . "-" . date('d-m-Y-H-i-s') . "-" . basename($_FILES["images"]["name"][$i]);

            $media->image = $filename[$i];
            $file_size = $_FILES['images']['size'][$i];
            $ext = end((explode(".", $filename)));
            $valid_ext = array('jpg','JPG','jpeg','JPEG','png','PNG','gif','GIF','mov','MOV','mp4','MP4');


        if(!empty($_FILES["images"]["tmp_name"][$i])){

            if($file_size > 104857600){
                $file_upload_error_messages.= "<div class=\"alert alert-danger alert-dismissable\">";
                $file_upload_error_messages.= "</div>";
            }   

            if(in_array($ext, $valid_ext)){
               }

               else{
                    $file_upload_error_messages.= "<div class=\"alert alert-danger alert-dismissable\">";
                    $file_upload_error_messages.= "</div>";
               }

            if(!empty($file_upload_error_messages)){
                $file_upload_error_messages.= "<div class=\"alert alert-danger alert-dismissable\">";
                $file_upload_error_messages.= "</div>";
            }       

            if(empty($file_upload_error_messages)){
                    if(move_uploaded_file($_FILES['images']['tmp_name'][$i],$target_directory."/".$shafilename)){
                        echo "<div class=\"alert alert-success alert-dismissable\">";
                        echo "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button>";
                        echo "</div>";

                             // Execute query
                             $stmt->execute(array($shafilename,'uploads/'.$position->order_id.'/'.$shafilename,$ext));

                }
            }
        } 
    }
    print_r($file_upload_error_messages);
}

現在我認為我可以使用此腳本(或在這里找到的類似腳本):

function handleFiles()
{
    var filesToUpload = document.getElementById('fileupload').files;
    var file = filesToUpload[0];

    // Create an image
    var img = document.createElement("img");
    // Create a file reader
    var reader = new FileReader();
    // Set the image once loaded into file reader
    reader.onload = function(e)
    {
        img.src = e.target.result;

        var canvas = document.createElement("canvas");
        //var canvas = $("<canvas>", {"id":"testing"})[0];
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var MAX_WIDTH = 400;
        var MAX_HEIGHT = 300;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);

        var dataurl = canvas.toDataURL("image/png");
        document.getElementById('image').src = dataurl;     
    }
    // Load files into file reader
    reader.readAsDataURL(file);
}

FileReader的腳本對我來說很清楚,除了那部分如何使用php重新上傳。 順便說一句,我比js更熟悉php,另一個問題是如何將此功能集成到我現有的腳本中...

我沒有外部上傳腳本,它們都在同一php文件中。

謝謝。

您不能在客戶端上縮小圖像並將其作為文件上傳,但是可以縮小圖像,然后獲取收縮圖像的dataURI並以字符串形式上傳,然后將其轉換回圖像。服務器端。

 var maxWidth = 100; var maxHeight = 100; document.getElementById("myfile").onchange = function() { var reader = new FileReader(); reader.onload = function(e) { var img = new Image(); img.onload = function() { var cnvs = document.createElement('canvas'); var rectRatio = img.width / img.height; var boundsRatio = maxWidth / maxHeight; var w, h; if (rectRatio > boundsRatio) { w = maxWidth; h = img.height * (maxWidth / img.width); } else { w = img.width * (maxHeight / img.height); h = maxHeight; } cnvs.width = w; cnvs.height = h; var ctx = cnvs.getContext('2d'); ctx.drawImage(img, 0, 0, w, h); var uri = cnvs.toDataURL(); // Do something here to upload the smaller verion of the datauri // for now i'm just putting it on the page though document.body.innerHTML = '<img src="' + uri + '">'; }; img.src = e.target.result; }; reader.readAsDataURL(this.files[0]); } 
 <input type=file id=myfile accept=".png"> 

然后在PHP端,您可以將其保存為這樣的實際映像

$data = $_POST['mydatauri'];
$encodedData = str_replace(' ','+',substr($data,strpos($data,",")+1));
$decodedData = base64_decode($encodedData);
file_put_contents("myUploadImage.png", $decodedData);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM