想要把圖片壓縮後再重新命名,在匯出成File,這樣的條件我原本以為很快就可以完成,沒想到花了我半天的時間,找尋解決方法,恩~~~那就來分享一下。
function resizeImage(file){
//新增一個Image
var img = new Image()
//使用 canvas 來讓圖片縮小之後在把
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
var MAX_WIDTH=fileData.width;
var MAX_HEIGHT=fileData.height;
img.onload = function(){
var img_width = img.width;
var img_height = img.height;
var scale = Math.min((MAX_WIDTH/img_width),(MAX_HEIGHT/img_height));
var img_width_scale = img_width*scale;
var img_height_scale = img_height*scale;
canvas.width = img_width_scale;
canvas.height = img_height_scale;
//canvas放到Image裡面
ctx.drawImage(img,0,0,img_width_scale,img_height_scale);
var imageData = {
///再變成"image/jpg"
base64:canvas.toDataURL("image/jpg"),
fileName:fileData.fileName
}
dataURLtoFile(imageData)
}
img.src = URL.createObjectURL(file)
}
//把base64換成file檔案
function dataURLtoFile(){
var arr = imageData.base64.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
var newFile = new File([u8arr], imageData.fileName, {type:mime});
commit('SET_RESIZE_IMAGE_FILE',newFile)
}