【无标题】

const dpi = window.devicePixelRatio >= 3 ? 3 : 2;
const qualitys = {
    webp: ['h', 'l', 'u'],
    jpg: ['h', 'l'],
    png: ['h'],
};
const compress = (url, width = 50, isAlpha, isRatio = true, quality = 'h') => {
    if (!url) {
        return '';
    }
    const reg =
        /-(c\.w\.i\d+|c\.w\d+|cw\.w\d+|fe\.w\d+|h\.w\d+|h\.w\.i\d+|icon|lw\d+|o\d+|o\.i\d+|w\d+|yyb|t\.w\d+)/;
    const matchResult = url && url.match(reg);
    if (matchResult) {
        url = url.slice(0, matchResult.index);
    }
    const ua = navigator.userAgent.toLowerCase();
    const isApple = /iphone|ipad|ios|mac/.test(ua);
    const iosMajorVersion = (ua.match(/(cpu\s+iphone\s+os|cpu\s+os)\s+(\d+)(_\d+){0,2}/) || [
        '',
        '',
        '0',
        '_0',
        '_0',
    ])[2];
    const appleWebpSupported = /chrome/.test(ua) || Number(iosMajorVersion) >= 14;
    let format = 'webp';
    if (isApple && !appleWebpSupported) {
        if (isAlpha) {
            format = 'png';
        } else {
            format = 'jpg';
        }
    }

    isRatio && (width = (width * dpi) / 2);
    const widthArr = [
        50, 70, 90, 120, 180, 207, 320, 360, 414, 540, 563, 640, 720, 750, 828, 960, 1080, 1125,
        1280, 1440, 1600, 2160,
    ];
    for (let i = 0, ii = widthArr.length; i < ii; i++) {
        if (width <= widthArr[i] || i === ii - 1) {
            width = widthArr[i];
            break;
        }
    }
    quality = qualitys[format].indexOf(quality) > -1 ? quality : 'h';
    return `${url}-t.w${width}.${format}.${quality}`;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值