<template>
<div>
<input
type="file"
id="avatar"
name="avatar"
accept="image/png, image/jpeg"
@change="loadFile"
/>
</div>
</template>
<script>
//@ canvas 壓縮圖片并保存原圖片exif信息 核心思路
//@ 保存原圖 Exif 信息羽圃,待圖片壓縮完成后,將原圖 Exif 信息拼接到壓縮圖上局骤。
//@ 校驗圖片base64圖片信息 地址: http://code.ciaoca.com/javascript/exif-js/demo/base64
//@ 參考: http://www.dirk.wang/2019/08/16/canvas%E5%8E%8B%E7%BC%A9jpg%E4%B8%A2%E5%A4%B1exif/
import EXIF from "exif-js";
var BasePage = zj.widgets.BasePage;
export default {
mixins: [BasePage],
components: {},
data() {
return {
exifInfo: "",
};
},
methods: {
loadFile(event) {
let file = event.target.files[0];
//讀取圖片的元信息
var orientation;
EXIF.getData(file, function () {
orientation = EXIF.getTag(this, "Orientation"); // 圖片旋轉(zhuǎn)的方向
});
let reader = new FileReader();
let that = this;
reader.onload = function () {
let result = this.result;
that.imgSrc = result;
// 保存原有圖片 exif信息
let orignBuffer = that.base64ToArrayBuffer(result);
let segments = that.getSegments(orignBuffer); //分割片段
that.exifInfo = that.getEXIF(segments);
//使用exif
that.getImgData(this.result, orientation, (data) => {
//這里可以使用校正后的圖片data了
var img = new Image();
img.src = data;
//圖片加載完畢之后進(jìn)行壓縮冯痢,然后上傳
if (img.complete) {
callback();
} else {
img.onload = callback;
}
function callback() {
var data = that.compress(img);
// 將原始圖片exif信息拼接到壓縮后的圖片base64之后
let orignBuffer = that.base64ToArrayBuffer(data);
let newImg = that.insertEXIF(orignBuffer, that.exifInfo);
let base64Img = that.transformArrayBufferToBase64(newImg);
console.log("base64Img", base64Img);
that.upload(base64Img, file.type, file.name);
}
});
};
reader.readAsDataURL(file);
return false;
},
//上傳圖片
upload(basestr, type, name) {
let text = window.atob(basestr.split(",")[1]);
let buffer = new ArrayBuffer(text.length);
let ubuffer = new Uint8Array(buffer);
for (let i = 0; i < text.length; i++) {
ubuffer[i] = text.charCodeAt(i);
}
let Builder = window.WebKitBlobBuilder || window.MozBlobBuilder;
let blob;
if (Builder) {
let builder = new Builder();
builder.append(buffer);
blob = builder.getBlob(type);
} else {
blob = new window.Blob([buffer], { type: type });
}
let formdata = new FormData();
// formdata.append(model, blob, name);
},
//壓縮圖片
compress(img) {
//用于壓縮圖片的canvas
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
// 瓦片canvas
var tCanvas = document.createElement("canvas");
var tctx = tCanvas.getContext("2d");
let initSize = img.src.length;
let width = img.width;
let height = img.height;
//如果圖片大于四百萬像素扳剿,計算壓縮比并將大小壓至400萬以下
var ratio;
if ((ratio = (width * height) / 4000000) > 1) {
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = 1;
}
canvas.width = width * 2;
canvas.height = height * 2;
//鋪底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
//如果圖片像素大于100萬則使用瓦片繪制
var count;
if ((count = (width * height) / 4000000) > 1) {
count = ~~(Math.sqrt(count) + 1); //計算要分成多少塊瓦片
//計算每塊瓦片的寬和高
var nw = ~~(width / count);
var nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (var i = 0; i < count; i++) {
for (var j = 0; j < count; j++) {
tctx.drawImage(
img,
i * nw * ratio,
j * nh * ratio,
nw * ratio * 2,
nh * ratio * 2,
0,
0,
nw,
nh
);
ctx.drawImage(tCanvas, i * nw, j * nh, nw * 2, nh * 2);
}
}
} else {
ctx.drawImage(img, 0, 0, width * 2, height * 2);
}
//進(jìn)行最小壓縮
let ndata = canvas.toDataURL("image/jpeg", 1);
console.log(
"壓縮前:" +
initSize +
"宪郊,壓縮后:" +
ndata.length +
"峡扩,壓縮率:" +
~~((100 * (initSize - ndata.length)) / initSize) +
"%"
);
return ndata;
},
getImgData(img, dir, next) {
// @param {string} img 圖片的base64
// @param {int} dir exif獲取的方向信息
// @param {function} next 回調(diào)方法蹭越,返回校正方向后的base64
var image = new Image();
image.onload = function () {
var degree = 0,
drawWidth,
drawHeight,
width,
height;
drawWidth = this.naturalWidth;
drawHeight = this.naturalHeight;
//以下改變一下圖片大小
var maxSide = Math.max(drawWidth, drawHeight);
if (maxSide > 1024) {
var minSide = Math.min(drawWidth, drawHeight);
minSide = (minSide / maxSide) * 1024;
maxSide = 1024;
if (drawWidth > drawHeight) {
drawWidth = maxSide;
drawHeight = minSide;
} else {
drawWidth = minSide;
drawHeight = maxSide;
}
}
var canvas = document.createElement("canvas");
canvas.width = width = drawWidth;
canvas.height = height = drawHeight;
var context = canvas.getContext("2d");
//判斷圖片方向,重置canvas大小教届,確定旋轉(zhuǎn)角度响鹃,iphone默認(rèn)的是home鍵在右方的橫屏拍攝方式
switch (dir) {
//iphone橫屏拍攝,此時home鍵在左側(cè)
case 3:
degree = 180;
drawWidth = -width;
drawHeight = -height;
break;
//iphone豎屏拍攝案训,此時home鍵在下方(正常拿手機(jī)的方向)
case 6:
canvas.width = height;
canvas.height = width;
degree = 90;
drawWidth = width;
drawHeight = -height;
break;
//iphone豎屏拍攝买置,此時home鍵在上方
case 8:
canvas.width = height;
canvas.height = width;
degree = 270;
drawWidth = -width;
drawHeight = height;
break;
}
//使用canvas旋轉(zhuǎn)校正
context.rotate((degree * Math.PI) / 180);
context.drawImage(this, 0, 0, drawWidth, drawHeight);
//返回校正圖片
next(canvas.toDataURL("image/jpeg", 0.4));
};
image.src = img;
},
//@ canvas 壓縮圖片保存原圖片exif核心代碼
// 工具函數(shù) 將 base64 轉(zhuǎn) ArrayBuffer
base64ToArrayBuffer(base64, contentType) {
contentType =
contentType || base64.match(/^data\:([^\;]+)\;base64,/im)[1] || ""; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
base64 = base64.replace(/^data\:([^\;]+)\;base64,/gim, "");
// btoa是binary to ascii,將binary的數(shù)據(jù)用ascii碼表示强霎,即Base64的編碼過程
// atob則是ascii to binary忿项,用于將ascii碼解析成binary數(shù)據(jù)
var binary = atob(base64);
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
return buffer;
},
transformArrayBufferToBase64(buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
for (var len = bytes.byteLength, i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return `data:image/jpeg;base64,${window.btoa(binary)}`;
},
// 獲取 0xFFE0~0xFFEF 開頭的應(yīng)用標(biāo)記片段
getSegments(arrayBuffer) {
var head = 0,
segments = [];
var length, endPoint, seg;
var arr = [].slice.call(new Uint8Array(arrayBuffer), 0);
while (true) {
// SOS(Start of Scan, 由 0xff 0xda 開頭)
// 遍歷到 SOS 表示已經(jīng)遍歷完所有標(biāo)記,再往下就是圖像數(shù)據(jù)流了,直接 break
if (arr[head] === 0xff && arr[head + 1] === 0xda) {
break;
}
// SOI(Start of Image)是 JPG 文件的開頭內(nèi)容轩触,由 0xff 0xd8 開頭
if (arr[head] === 0xff && arr[head + 1] === 0xd8) {
head += 2;
}
// 找出每個標(biāo)記片段
else {
// 每個標(biāo)記開頭后跟著的兩個字節(jié)記錄了該標(biāo)記所記錄內(nèi)容的長度
length = arr[head + 2] * 256 + arr[head + 3]; // 內(nèi)容長度
endPoint = head + length + 2; // 內(nèi)容結(jié)束位置
// 從0xff開頭寞酿,到標(biāo)記數(shù)據(jù)內(nèi)容結(jié)束全部截出來
seg = arr.slice(head, endPoint);
head = endPoint;
// push整個標(biāo)記信息
segments.push(seg);
}
if (head > arr.length) {
break;
}
}
return segments;
},
// 從標(biāo)記片段篩選 & 取出 exif 信息
getEXIF(segments) {
if (!segments.length) {
return [];
}
var seg = [];
for (var x = 0; x < segments.length; x++) {
var s = segments[x];
// 0xff 0xe1開頭的才是 exif數(shù)據(jù)(即app1)
if (s[0] === 0xff && s[1] === 0xe1) {
// app1 exif 0xff 0xe1
seg = seg.concat(s);
}
}
return seg;
},
// 拼接 Exif 到壓縮后的 base64 中:
// 插入 Exif 信息
insertEXIF(resizedImg, exifArr) {
var arr = [].slice.call(new Uint8Array(resizedImg), 0);
//不是標(biāo)準(zhǔn)的JPEG文件
if (arr[2] !== 0xff || arr[3] !== 0xe0) {
return resizedImg;
}
var app0_length = arr[4] * 256 + arr[5]; //兩個字節(jié)
// 拼接文件 SOI + EXIF + 去除APP0的圖像信息
var newImg = [0xff, 0xd8].concat(exifArr, arr.slice(4 + app0_length));
return new Uint8Array(newImg);
},
},
};
</script>
canvas 壓縮圖片并保存原圖片exif信息
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來板壮,“玉大人逗鸣,你說我怎么就攤上這事〈戮” “怎么了撒璧?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長笨使。 經(jīng)常有香客問我卿樱,道長,這世上最難降的妖魔是什么硫椰? 我笑而不...
- 正文 為了忘掉前任繁调,我火速辦了婚禮,結(jié)果婚禮上靶草,老公的妹妹穿的比我還像新娘蹄胰。我一直安慰自己,他們只是感情好奕翔,可當(dāng)我...
- 文/花漫 我一把揭開白布裕寨。 她就那樣靜靜地躺著,像睡著了一般派继。 火紅的嫁衣襯著肌膚如雪宾袜。 梳的紋絲不亂的頭發(fā)上,一...
- 文/蒼蘭香墨 我猛地睜開眼节视,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了假栓?” 一聲冷哼從身側(cè)響起寻行,我...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡牙丽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年简卧,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片烤芦。...
- 正文 年R本政府宣布遂唧,位于F島的核電站芙代,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏盖彭。R本人自食惡果不足惜纹烹,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望召边。 院中可真熱鬧铺呵,春花似錦、人聲如沸掌实。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽贱鼻。三九已至宴卖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間邻悬,已是汗流浹背症昏。 一陣腳步聲響...
- 正文 我出身青樓掘宪,卻偏偏與公主長得像,于是被迫代替她去往敵國和親攘烛。 傳聞我的和親對象是個殘疾皇子魏滚,可洞房花燭夜當(dāng)晚...