87 lines
2.3 KiB
JavaScript
87 lines
2.3 KiB
JavaScript
/**
|
||
* 图片压缩
|
||
* imgSrc 地址
|
||
* scale 压缩质量 0-1
|
||
* type 文件类型
|
||
*/
|
||
export async function H5compressImg(
|
||
imgSrc,
|
||
scale = 0.75,
|
||
maxWidth = 800,
|
||
maxHeight = 800
|
||
) {
|
||
return new Promise((resolve, reject) => {
|
||
var img = new Image();
|
||
img.src = imgSrc;
|
||
img.onload = () => {
|
||
// 计算按比例压缩后的尺寸
|
||
let w = img.width;
|
||
let h = img.height;
|
||
// 如果图片宽度或高度超过最大限制,则按比例缩放
|
||
if (w > maxWidth) {
|
||
h = (maxWidth / w) * h;
|
||
w = maxWidth;
|
||
}
|
||
if (h > maxHeight) {
|
||
w = (maxHeight / h) * w;
|
||
h = maxHeight;
|
||
}
|
||
var canvas = document.createElement("canvas");
|
||
var ctx = canvas.getContext("2d");
|
||
// 设置canvas的宽高
|
||
canvas.width = w;
|
||
canvas.height = h;
|
||
// 将图片绘制到canvas上
|
||
ctx.drawImage(img, 0, 0, w, h);
|
||
// 设置输出格式为jpeg,质量为scale
|
||
var base64;
|
||
try {
|
||
base64 = canvas.toDataURL("image/jpeg", scale);
|
||
} catch (e) {
|
||
// 如果浏览器不支持jpeg,或者有跨域问题,则使用png
|
||
base64 = canvas.toDataURL("image/png", scale);
|
||
}
|
||
canvas = null;
|
||
resolve(base64);
|
||
};
|
||
img.onerror = (e) => {
|
||
reject(e);
|
||
};
|
||
});
|
||
}
|
||
/**base转Blob */
|
||
export function base64ToBlob(base64) {
|
||
var arr = base64.split(","),
|
||
mime = arr[0].match(/:(.*?);/)[1],
|
||
bstr = atob(arr[1]),
|
||
n = bstr.length,
|
||
u8arr = new Uint8Array(n);
|
||
while (n--) {
|
||
u8arr[n] = bstr.charCodeAt(n);
|
||
}
|
||
return new Blob([u8arr], {
|
||
type: mime,
|
||
});
|
||
}
|
||
/**获取base64的文件大小 */
|
||
export function getBase64Size(base64Str) {
|
||
let size = 0;
|
||
if (base64Str) {
|
||
// 获取base64图片byte大小
|
||
const equalIndex = base64Str.indexOf("="); // 获取=号下标
|
||
if (equalIndex > 0) {
|
||
const str = base64Str.substring(0, equalIndex); // 去除=号
|
||
const strLength = str.length;
|
||
const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
|
||
size = Math.floor(fileLength); // 向下取整
|
||
} else {
|
||
const strLength = base64Str.length;
|
||
const fileLength = strLength - (strLength / 8) * 2;
|
||
size = Math.floor(fileLength); // 向下取整
|
||
}
|
||
} else {
|
||
size = null;
|
||
}
|
||
return size;
|
||
}
|