2017-04-21 77 views
-1

我試圖將JavaScript調整大小的圖像上傳到服務器。
所以我試圖設置文件輸入調整大小的圖像。
之後,我才知道we cannot change file input unless user select file
現在我試圖要求用戶將調整大小的圖像保存到他的本地磁盤,以便他可以重新附加該文件。
我的問題是:我如何將由JavaScript完成的調整大小的圖像保存到本地磁盤。使用JavaScript調整圖像大小並保存到磁盤

+3

替換這些兩行。然後通過php使用'base64_decode($ base64string)'和'file_put_contents($ file_path,$ base64stringdecoded);'將文件保存到所需的路徑 –

+0

@ Deep3015您的鏈接是有幫助的。其實我現在無法更改我的完整網站代碼。所以我試圖修改文件輸入是調整大小的圖像。我改變了我的問題。可能是你可以再次幫助我。 –

+0

我認爲沒有辦法。或者要求用戶重新上傳圖片或更改代碼。 –

回答

2

最後,我自己解決了這個問題,並在此爲未來的讀者添加我的解決方案。

$(document).on("change", ":file", function(event) 
{ 
    if(this.files && this.files[0]) 
    { 
     var file_input=$(this); 
     var file=this.files[0]; 
     var file_type=file.type; 
     if(file_type && file_type.substr(0,5)=="image") 
     { 
      var img = document.createElement("img"); 
      var reader = new FileReader(); 
      reader.onload = function (e) 
      { 
       img.src = e.target.result; 
       img.onload = function (imageEvent) 
       { 
        var MAX_WIDTH = 800; 
        var MAX_HEIGHT = 600; 
        var width = img.naturalWidth; 
        var height = img.naturalHeight; 
        //resize the image if it higher than MAX_WIDTH or MAX_HEIGHT 
        if((width>MAX_WIDTH)||(height>MAX_HEIGHT)) 
        { 
         if((width/height)>(MAX_WIDTH/MAX_HEIGHT)) 
         { 
          height *= MAX_WIDTH/width; 
          width = MAX_WIDTH; 
         } 
         else 
         { 
          width *= MAX_HEIGHT/height; 
          height = MAX_HEIGHT; 
         } 
         var canvas = document.createElement("canvas"); 
         canvas.width = width; 
         canvas.height = height; 
         var ctx = canvas.getContext("2d"); 
         ctx.drawImage(img, 0, 0, width, height); 
         //following two lines saves the image 
         var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 
         window.location.href=image; // 
         //file_input.val(null);//if you want reset file input 
         //file_input.trigger('click'); //if you want to reopen file input       

        } 
       }; 

      }; 
      reader.readAsDataURL(file); 
     } 

    } 
    else 
    { 
     console.log('no file attached'); 
    } 
}); 

這兩條線將文件保存

var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 
window.location.href=image; 

遺憾的是它不使用一個很好的文件名保存。所以我用另一種方法取代了這兩條線。

here下載FileSaver.js並將其包含到腳本中。 現在可以如果使用的是[croppie](https://foliotek.github.io/Croppie/),然後在調整其大小被轉換成BASE64圖像串與這些代碼

canvas.toBlob(function(blob) 
{ 
    saveAs(blob, 'image.png'); 
    //saveAs(blob, file.name);//or this one 
});