前端圖片壓縮Canvas

?????圖片壓縮Canvas

#關(guān)于如何實(shí)現(xiàn)壓縮

查閱MDN找到的是這個(gè)API:

HTMLCanvasElement.toBlob()?方法創(chuàng)造Blob對象,用以展示canvas上的圖片;這個(gè)圖片文件可以被緩存或保存到本地,由用戶代理端自行決定。如不特別指明,圖片的類型默認(rèn)為?image/png,分辨率為96dpi。

// callback處理blob主要,type圖片類型,encoderOptions圖片壓縮比例 0-1

canvas.toBlob(callback, type, encoderOptions);

Demo


這里看到壓縮效果已經(jīng)由原來的8.5Mb到了1.6Mb左右,這里有個(gè)問題Mac上面的壓縮效果沒Win好(尷尬了)。


#實(shí)現(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">點(diǎn)擊上傳</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大小設(shè)置

? ? ? ? ? ? ? ? ? ? ctx.drawImage(img, 0, 0, width, height);

? ? ? ? ? ? ? ? ? ? // 植入內(nèi)容

? ? ? ? ? ? ? ? ? ? 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()

首先需要的是利用這個(gè)API來讀取文件,實(shí)例化之后采用 readAsDataURL 的方式來讀取圖片的資源路徑,這里的兼容性不錯(cuò),囊闊了幾乎所有瀏覽器版本和平臺。


reader.readAsDataURL(file); //這樣讀取圖片,上述例子可以多選操作,所以循環(huán)了下


2.reader.onload的回調(diào)中創(chuàng)建圖片

// 創(chuàng)建圖片內(nèi)容constimg =newImage();// 將圖片地址綁定到base64,這里遇到一個(gè)問題采用event.target.result取不到當(dāng)前,reader下面有result屬性可用img.src = reader.result;


3.創(chuàng)建畫布,繪制圖片內(nèi)容

// 創(chuàng)建canvas畫布

const elem = document.createElement('canvas');

// 設(shè)置畫布大小

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.劃重點(diǎn)壓縮,將canvas壓縮大小轉(zhuǎn)為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這里有點(diǎn)玄學(xué)變大了 超過1 或者小于0 大小大概壓縮了6成左右




#補(bǔ)充

這里看到一個(gè)兼容性的問題,主要考慮的Sarari IOS上,誰叫客戶用呢?


// MDN給除了兼容代碼,大體是是在Object原型添加了toBlob函數(shù)實(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'} ) );

? ? ? });

? ? }

? });

}

#參考資料

MIME 類型

HTMLCanvasElement.toBlob()

FileReader

Canvas API

CanvasRenderingContext2D.drawImage()


查看原文

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容