【JS压缩图片】js压缩图片至指定大小
码
yaSuoImg.js
/*** 加载图片* @param {URL} url 图片地址* @returns {Promise.<Image>}*/
const loadImageAsync = (url) => {return new Promise((resolve, reject) => {const image = new Image();image.src = url;image.onload = function () {resolve(image);};image.onerror = function (err) {reject(new Error("出错 " + err));};});
}/*** 图片压缩* @param {File} file 拾取的图片文件File* @param {Number} [maxSizeKB=300] 超过maxSizeKB启动压缩(KB)* @param {String} [imgType="webp"] 压缩后的图片格式,推荐webp,既无损压缩* @param {Number} [opy=.9] 清晰度 0-1 推荐0.9,既不失真,又可压缩图片内存* @return {Promise.<Base64URLString>}*/
export const compress = async (file, maxSizeKB = 300, imgType = 'webp', opy = .9) => {const canvas = document.createElement("canvas"),context = canvas.getContext("2d"),image = await loadImageAsync(URL.createObjectURL(file)),{ height, width } = image;if (file.size > maxSizeKB * 1024) {let rate = 0; // 压缩率 const fileSizeKB = file.size / 1024; // 文件大小KB, file.size给的是字节Byteif (fileSizeKB > maxSizeKB) { // 当图片大小超标,才进行压缩rate = (fileSizeKB - maxSizeKB) / fileSizeKB; // 计算压缩率}// 纠正因子,不加会导致压缩出的文件太小const factor = 0,cvWidth = width * (1 - rate + factor),cvHeight = height * (1 - rate + factor);canvas.height = cvHeight;canvas.width = cvWidth;context.clearRect(0, 0, cvWidth, cvHeight);context.drawImage(image, 0, 0, cvWidth, cvHeight);} else {canvas.height = height;canvas.width = width;opy = .7context.clearRect(0, 0, width, height);context.drawImage(image, 0, 0, width, height);}URL.revokeObjectURL(file)//释放内存return canvas.toDataURL(`image/${imgType}`, opy);
}
用
import { compress } from "/yaSuoImg.js";
const imgBlobSrc = await compress(file);
``