阅读 1005

纯Js 使用canvas等比缩放,压缩图片

直接上代码:


/**
 * 计算缩放宽高
 * @param imgWidth 图片宽
 * @param imgHeight 图片高
 * @param maxWidth 期望的最大宽
 * @param maxHeight 期望的最大高
 * @returns [number,number] 宽高
 */
export const zoomImgSize = (imgWidth, imgHeight, maxWidth, maxHeight) => {
    let newWidth = imgWidth,
        newHeight = imgHeight;
    if (imgWidth / imgHeight >= maxWidth / maxHeight) {
        if (imgWidth > maxWidth) {
            newWidth = maxWidth;
            newHeight = (imgHeight * maxWidth) / imgWidth;
        }
    } else {
        if (imgHeight > maxHeight) {
            newHeight = maxHeight;
            newWidth = (imgWidth * maxHeight) / imgHeight;
        }
    }
    if (newWidth > maxWidth || newHeight > maxHeight) {
        //不满足预期,递归再次计算
        return zoomImgSize(newWidth, newHeight, maxWidth, maxHeight);
    }
    return [newWidth, newHeight];
};

/**
 * 压缩图片
 * @param img img对象
 * @param maxWidth 最大宽
 * @param maxHeight 最大高
 * @param quality 压缩质量
 * @returns {string|*} 返回base64
 */
export const resizeImg = (img, maxWidth, maxHeight, quality = 1) => {
    const imageData = img.src;
    if (imageData.length < maxWidth * maxHeight) {
        return imageData;
    }
    const imgWidth = img.width;
    const imgHeight = img.height;
    if (imgWidth <= 0 || imgHeight <= 0) {
        return imageData;
    }
    const canvasSize = zoomImgSize(imgWidth, imgHeight, maxWidth, maxHeight);
    const canvas = document.createElement('canvas');
    canvas.width = canvasSize[0];
    canvas.height = canvasSize[1];
    canvas.getContext('2d')
        .drawImage(img, 0, 0, canvas.width,
            canvas.height);
    return canvas.toDataURL('image/jpeg', quality);
};
复制代码

一个计算缩放后的宽高.一个压缩图片.

当然也可以再优化扩展一下,比如压缩后的图片格式,img的判空等等.

文章分类
前端
文章标签