merchapp/java-mall-app-shop-admin/utils/tool.js
2025-06-26 02:09:26 +08:00

72 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 图片压缩
* imgSrc 地址
* scale 压缩质量 0-1
* type 文件类型
*/
export async function H5compressImg(imgSrc, scale) {
//imgSrc:图片的路径
//scale:缩放比例 0-1之间
return new Promise((reslove, reject) => {
var img = new Image(); //创建Image对象生成一个<img>标签
img.src = imgSrc; //将图片路径赋给<img>标签的src
img.onload = () => {
//onload在图片加载成功后触发在onload中完成压缩功能
var h = img.height / 2; // 获取原本图片的宽高
var w = img.width / 2; //默认按比例压缩,根据需求修改
var canvas = document.createElement("canvas"); //创建画布
var ctx = canvas.getContext("2d"); //设置为2d效果
var width = document.createAttribute("width"); //创建属性节点
width.nodeValue = w; //设置属性值
var height = document.createAttribute("height");
height.nodeValue = h;
canvas.setAttributeNode(width); //设置画布宽高
canvas.setAttributeNode(height);
ctx.drawImage(img, 0, 0, w, h); //将图片贴到画布上
//img:图片 0,0:粘贴的位置 w,h:粘贴图片的大小
var base64 = canvas.toDataURL("image/png", scale);
//'image/png':压缩返回图片的类型 scale:图片质量
//如果要base64的流可以直接将结果返回了
canvas = null; //清除画布
// var blob = base64ToBlob(base64); //需要二进制流调用该方法拿到
// let blobUrl = window.URL.createObjectURL(blob); //blob地址
reslove(base64);
};
});
}
/**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;
}