img-src-handle.js 1.84 KB
require('./webp-support');

const defaultQuality = 60;

/**
 * 图片链接处理
 */
const imgSrcHandle = (imgUrl, params) => {
    if (!imgUrl) {
        return imgUrl;
    }

    params = Object.assign({
        q: defaultQuality
    }, params);

    let splits = imgUrl.split('?');
    let url = splits[0];
    let query = splits[1] || '';

    if (!query || query === 'imageslim') {
        if (window.supportWebp) {
            url += `?imageView2/0/interlace/1/format/webp/q/${params.q}`;
        } else {
            let extQuery = params.q === defaultQuality ? '?imageslim' : `?imageView2/0/interlace/1/q/${params.q}`;

            url += extQuery;
        }
        imgUrl = url;
    } else if (/imageView/.test(query)) { // imageView2 || imageView
        if (!/\/q\/\d+/.test(query)) {
            imgUrl += `/q/${params.q}`;
        } else {
            imgUrl = imgUrl.replace(/\/q\/\d+/g, '/q/' + params.q);
        }

        if (window.supportWebp && !/format\//i.test(query)) {
            imgUrl += '/format/webp';
        }

        if (window.supportWebp && (/format\/png/i.test(query) || /format\/jpg/i.test(query))) {
            imgUrl = imgUrl.replace(/format\/png/i, 'format/webp').replace(/format\/jpg/i, 'format/webp');
        }
    } else if (/imageMogr/.test(query)) {
        if (!/\/quality\/\d+/.test(query)) {
            imgUrl += `/quality/${params.q}`;
        } else {
            imgUrl = imgUrl.replace(/\/quality\/\d+/g, '/quality/' + params.q);
        }

        if (window.supportWebp && !/format\//.test(query)) {
            imgUrl += '/format/webp';
        }

        if (window.supportWebp && (/format\/png/i.test(query) || /format\/jpg/i.test(query))) {
            imgUrl = imgUrl.replace(/format\/png/i, 'format/webp').replace(/format\/jpg/i, 'format/webp');
        }
    }
    return imgUrl;
};

module.exports = imgSrcHandle;