1. ホーム
  2. Web制作
  3. html5

アップロード用画像の圧縮にcanvasを使用した例

2022-01-14 02:46:11

プラグインのuiとプロトタイプが異なるので、自分でメソッドを書きました。

まず、アップロードボタンが必要です。

<input type="file" id="fileys" class="fileys" @change="uploadFile($event)" accept=" image/*"/>
<! --uploadFile uses change because. The user may repeatedly select other images -->


本題に入る。

uploadFile:function(event){
let file = event.target.files[0]; // get the image file value of input
let param = new FormData(); // create form object
if(param.getAll('file')[0] == "undefined"){
        return false // determine if it is empty
      }
      
 let reader = new FileReader() 
  reader.readAsDataURL(file) //read the file and save the file as a URL in the resulr property base64 format ,,, the online documentation seems to specify the format. I chose a base64
  
  
  reader.onload = function(e) { // triggered when the file is read  
      let result = e.target.result // base64 format image address  
      var image = new Image()
      image.src = result // set the image's address to the base64 address  
      image.onload = function(){  
        var canvas = document.getElementById("canvas");  
        var context = canvas.getContext("2d");  
        canvas.width = image.width; // set the canvas width of the canvas to the image width  
        canvas.height = image.height; 
        context.drawImage(image, 0, 0, image.width, image.height) // draw the image on the canvas  
        let dataUrl = canvas.toDataURL('image/jpeg', 0.001) // set the compression ratio, you can set it as needed, setting it too small will affect the image quality, dataUrl is the compressed image resource, you can upload it to the server  
  let tupian = _this.dataURLtoFile(dataUrl, file.name)
        param.append('file', tupian);//corresponds to the background receiving the image name 

        //Then here you can write the axios method. Go and upload this param to the backend

           } 
       } 
  
}



以上、本記事の全内容をご紹介しましたが、皆様の学習のお役に立てれば幸いです。また、Script Houseをより一層ご支援いただければ幸いです。