在開發 H5 應用的時候碰到一個問題,應用只需要一張小的縮略圖,而用戶用手機上傳的確是一張大圖,手機攝像機拍的圖片好幾 M,這可要浪費很多流量。
像我這么為用戶著想的程序員,絕對不會讓這種事情發生的,于是就有了本文。
獲取圖片
通過 File API 獲取圖片。
var input = document.createElement('input');
input.type = 'file';
input.addEventListener('change', function() {
var file = this.files[0];
});
input.click();
預覽圖片
使用 createObjectURL() 或者 FileReader 預覽圖片
var img = document.createElement('img');
img.src = window.URL.createObjectURL(file);
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e) {
img.src = e.target.result;
}
reader.readAsDataURL(file);
使用 canvas 做縮略圖
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
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;
ctx.drawImage(img, 0, 0, width, height);
上傳縮略圖
canvas.toBlob(function(blob) {
var form = new FormData();
form.append('file', blob);
fetch('/api/upload', {method: 'POST', body: form});
});
結語
DEMO:weekcool.com/js/upload.j…
總結
以上所述是小編給大家介紹的HTML5 實現圖片上傳預處理功能,希望對大家有所幫助!