?????圖片壓縮Canvas
#關于如何實現(xiàn)壓縮
查閱MDN找到的是這個API:
HTMLCanvasElement.toBlob()?方法創(chuàng)造Blob對象论衍,用以展示canvas上的圖片;這個圖片文件可以被緩存或保存到本地,由用戶代理端自行決定定拟。如不特別指明,圖片的類型默認為?image/png蒋畜,分辨率為96dpi蹦魔。
// callback處理blob主要,type圖片類型铁追,encoderOptions圖片壓縮比例 0-1
canvas.toBlob(callback, type, encoderOptions);
這里看到壓縮效果已經(jīng)由原來的8.5Mb到了1.6Mb左右,這里有個問題Mac上面的壓縮效果沒Win好(尷尬了)季蚂。
#實現(xiàn)代碼
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? ? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? ? <title>Document</title>
? ? <style>
? ? ? ? body{
? ? ? ? ? ? padding: 20px 0;
? ? ? ? }
? ? ? ? #fileSelect{
? ? ? ? ? ? margin-top: 10px;
? ? ? ? ? ? padding: 10px 5px;
? ? ? ? ? ? border: 1px solid chartreuse;
? ? ? ? ? ? border-radius: 5px;
? ? ? ? ? ? background: green;
? ? ? ? ? ? color: white;
? ? ? ? ? ? text-decoration: none;
? ? ? ? }
? ? ? ? #fileSelect:hover{
? ? ? ? ? ? opacity: 0.8;
? ? ? ? }
? ? </style>
</head>
<body>
? ? <input type="file" id="fileElem" multiple accept="image/*" style="display:none"
? ? ? ? onchange="handleFiles(event,this.files)">
? ? <a href="#" id="fileSelect">點擊上傳</a>
</body>
<script>
? ? window.onload = function () {
? ? ? ? var fileSelect = document.getElementById("fileSelect"),
? ? ? ? ? ? fileElem = document.getElementById("fileElem");
? ? ? ? fileSelect.addEventListener("click", function (e) {
? ? ? ? ? ? if (fileElem) {
? ? ? ? ? ? ? ? fileElem.click(); // input文件上傳
? ? ? ? ? ? }
? ? ? ? ? ? e.preventDefault();
? ? ? ? }, false);
? ? }
? ? function handleFiles(e, files) {
? ? ? ? for (var i = 0; i < files.length; i++) {
? ? ? ? ? ? var file = files[i];
? ? ? ? ? ? var imageType = /^image\//;
? ? ? ? ? ? if (!imageType.test(file.type)) {
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
? ? ? ? ? ? console.log(file);
? ? ? ? ? ? const width = 500;
? ? ? ? ? ? const height = 300;
? ? ? ? ? ? const fileName = file.name;
? ? ? ? ? ? const reader = new FileReader();
? ? ? ? ? ? reader.readAsDataURL(file);
? ? ? ? ? ? reader.onload = event => {
? ? ? ? ? ? ? ? const img = new Image();
? ? ? ? ? ? ? ? img.src = reader.result;
? ? ? ? ? ? ? ? img.onload = () => {
? ? ? ? ? ? ? ? ? ? const elem = document.createElement('canvas');
? ? ? ? ? ? ? ? ? ? elem.width = width;
? ? ? ? ? ? ? ? ? ? elem.height = height;
? ? ? ? ? ? ? ? ? ? const ctx = elem.getContext('2d');
? ? ? ? ? ? ? ? ? ? // canvas大小設置
? ? ? ? ? ? ? ? ? ? ctx.drawImage(img, 0, 0, width, height);
? ? ? ? ? ? ? ? ? ? // 植入內容
? ? ? ? ? ? ? ? ? ? document.body.append(elem);
? ? ? ? ? ? ? ? ? ? //--------- 如果不需要資源上傳,只需顯示琅束,下面代碼可以不要了------
? ? ? ? ? ? ? ? ? ? ctx.canvas.toBlob((blob) => {
? ? ? ? ? ? ? ? ? ? ? ? const file = new File([blob], fileName, {
? ? ? ? ? ? ? ? ? ? ? ? ? ? type: 'image/jpeg',
? ? ? ? ? ? ? ? ? ? ? ? ? ? lastModified: Date.now()
? ? ? ? ? ? ? ? ? ? ? ? });
? ? ? ? ? ? ? ? ? ? ? ? console.log(file); // file為壓縮后的圖片
? ? ? ? ? ? ? ? ? ? }, 'image/jpeg', 10e-9);
? ? ? ? ? ? ? ? ? ? // ----------------------
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? reader.onerror = error => console.log(error);
? ? ? ? ? ? };
? ? ? ? }
? ? }
</script>
</html>
#流程
1.new FileReader()
首先需要的是利用這個API來讀取文件扭屁,實例化之后采用 readAsDataURL 的方式來讀取圖片的資源路徑,這里的兼容性不錯,囊闊了幾乎所有瀏覽器版本和平臺涩禀。
reader.readAsDataURL(file); //這樣讀取圖片料滥,上述例子可以多選操作,所以循環(huán)了下
2.reader.onload的回調中創(chuàng)建圖片
// 創(chuàng)建圖片內容constimg =newImage();// 將圖片地址綁定到base64,這里遇到一個問題采用event.target.result取不到當前艾船,reader下面有result屬性可用img.src = reader.result;
3.創(chuàng)建畫布葵腹,繪制圖片內容
// 創(chuàng)建canvas畫布
const elem = document.createElement('canvas');
// 設置畫布大小
elem.width = width;
elem.height = height;
//獲取???
const ctx = elem.getContext('2d')
// 繪制
ctx.drawImage(img, 0, 0, width, height); // drawImage這里查看MDN文檔即可
// 植入頁面
document.body.append(elem);
4.劃重點壓縮,將canvas壓縮大小轉為image對象
ctx.canvas.toBlob((blob) => {
? ? const file = new File([blob], fileName, {
? ? ? ? type: 'image/jpeg', // 這里的格式可以是jpg屿岂,png践宴,gif,png等爷怀,都試了下阻肩,壓縮大小不變
? ? ? ? lastModified: Date.now()
? ? });
? ? console.log(file);
}, 'image/jpeg', 10e-9); // 這里的10e-9很小了 極限0-1 0是最大壓縮比率, 1這里有點玄學變大了 超過1 或者小于0 大小大概壓縮了6成左右
#補充
這里看到一個兼容性的問題,主要考慮的Sarari IOS上运授,誰叫客戶用呢烤惊?
// MDN給除了兼容代碼乔煞,大體是是在Object原型添加了toBlob函數(shù)實現(xiàn),粘貼添加就好
if (!HTMLCanvasElement.prototype.toBlob) {
? Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
? ? value: function (callback, type, quality) {
? ? ? var dataURL = this.toDataURL(type, quality).split(',')[1];
? ? ? setTimeout(function() {
? ? ? ? var binStr = atob( dataURL ),
? ? ? ? ? ? len = binStr.length,
? ? ? ? ? ? arr = new Uint8Array(len);
? ? ? ? for (var i = 0; i < len; i++ ) {
? ? ? ? ? arr[i] = binStr.charCodeAt(i);
? ? ? ? }
? ? ? ? callback( new Blob( [arr], {type: type || 'image/jpeg'} ) );
? ? ? });
? ? }
? });
}
#參考資料
CanvasRenderingContext2D.drawImage()