ionic 压缩图片
通过降低图片分辨率和画质压缩图片。
基础函数
通过 url 读取图片。
readImg(path: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
// ionic3
const url = normalizeURL(path);
// ionic4
const url = (window as any).Ionic.WebView.convertFileSrc(path);
let img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
resolve(img);
img = null;
};
img.onerror = () => {
reject(`圖片加載失敗:${url}`);
img = null;
};
img.src = url;
});
}
复制代码
dataURL 转 Blob
dataURLtoBlob(dataURL: string): Blob {
const arr = dataURL.split(',');
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const type = arr[0].match(/:(.*?);/)[1];
return new Blob([u8arr], { type });
}
复制代码
压缩图片
async imageResizer(
source: any,
parame?: {
quality?: number;
resultType?: 'blob' | 'dataURL';
maxSize: number;
}
): Promise<any> {
let path: string;
const options = {
quality: 0.9,
resultType: 'blob',
maxSize: 480
};
Object.assign(options, parame);
if (source instanceof Blob) {
path = await this.blobToDataURL(source);
} else {
path = source;
}
let img = await this.readImg(path);
let targetWidth: number;
let targetHeight: number;
// 图片比例
const ratio = img.width / img.height;
targetWidth = img.width > options.maxSize ? options.maxSize : img.width;
targetHeight = +(targetWidth / ratio).toFixed(0);
let canvas = <HTMLCanvasElement>document.createElement('CANVAS'),
ctx = canvas.getContext('2d');
canvas.width = targetWidth;
canvas.height = targetHeight;
ctx.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
// 检测有没有透明数据
const imageData = ctx.getImageData(0, 0, targetWidth, targetHeight).data;
let isAlphaBackground = false;
let length = imageData.length;
for (let index = 3; index < length; index += 4) {
if (imageData[index] !== 255) {
isAlphaBackground = true;
break;
}
}
// 透明為png、不透明轉換成jng
const type = isAlphaBackground ? 'image/png' : 'image/jpeg';
const dataURL = canvas.toDataURL(type, options.quality);
canvas = img = ctx = null;
if (options.resultType === 'blob') {
return this.dataURLtoBlob(dataURL);
} else {
return dataURL;
}
}
复制代码