helper.js 2.27 KB
var regExpWidth = new RegExp('{width}', 'g');
var regExpHeight = new RegExp('{height}', 'g');
var regExpMode = new RegExp('{mode}', 'g');
var regExpQg = new RegExp('/q/d+', 'g');
var regExpQ = new RegExp('/q/d+');
var regExpQuality = new RegExp('/quality/d+');
var regExpQualityg = new RegExp('/quality/d+', 'g');
var regExpImageView = new RegExp('imageView');
var regExpImageMogr = new RegExp('imageMogr');

var defaultQuality = 75;

function image(imgUrl, w, h, mode, q) {
  var urls,
    query,
    url;

  var params = {
    w: w,
    h: h,
    mode: mode || 2,
    q: q || defaultQuality
  };

  if (imgUrl && (typeof imgUrl === 'string')) {
    urls = imgUrl.split('?');
    query = urls[1] || '';
    url = urls[0];

    if (url.indexOf('http:') === 0) {
      url = url.replace('http:', 'https:');
    }

    if (!query || query === 'imageslim') {
      url += params.q === defaultQuality ? '?imageslim' : '?imageView2/0/interlace/1/q/' + params.q;
      imgUrl = url;
    } else {
      imgUrl = imgUrl.replace(regExpWidth, params.w)
        .replace(regExpHeight, params.h)
        .replace(regExpMode, (params.mode));

      if (regExpImageView.test(query)) { // imageView2 || imageView
        if (!regExpQ.test(query)) {
          imgUrl += '/q/' + params.q;
        } else {
          imgUrl = imgUrl.replace(regExpQg, '/q/' + params.q);
        }
      } else if (regExpImageMogr.test(query)) {
        if (!regExpQuality.test(query)) {
          imgUrl += '/quality/' + params.q;
        } else {
          imgUrl = imgUrl.replace(regExpQualityg, '/quality/' + params.q);
        }
      }
    }
    return imgUrl;
  } else {
    return '';
  }
}

// 如果图片没有imageView2,则默认添加imageView2
function imgView(imgSrc, w, h, mode, q) {
  var imgUrl = imgSrc || '';
  var indexOf = imgUrl.indexOf('?');

  if (!imgUrl) {
    return '';
  }

  if (imgUrl.indexOf('http://') === imgUrl.indexOf('https://')) {
    return imgUrl;
  }

  if (['http://', 'https://'].indexOf((imgUrl || '')) === -1) {
    return imgUrl;
  }

  if (indexOf === -1) {
    imgUrl += '?imageView2/{mode}/w/{width}/h/{height}';
    return image(imgUrl, w, h, mode, q);
  }

  if (indexOf > -1) {
    return image(imgUrl, w, h, mode, q);
  }

  return imgUrl;
}

module.exports = {
  image: image,
  imgView: imgView
};