image-handler.js 1.09 KB
const MAX_WIDTH = 1000;

export function getArticleImageSize({width, height, MIN_SCALE = 0.75}) {
  width = +width;
  height = +height;
  if (width > MAX_WIDTH) {
    height = height / (width / MAX_WIDTH);
    width = MAX_WIDTH;
  }

  if (MIN_SCALE && width / height < MIN_SCALE) {
    height = width / MIN_SCALE;
  }
  if (width === 1) {
    width = MAX_WIDTH;
  }
  if (height === 1) {
    height = MAX_WIDTH;
  }
  return {width, height};
}

export function processImage(src, mode, width, height, webp) {
  let splits = (src || '').split('?');
  const imgName = splits[0] || '';
  let query = splits[1] || '';

  if (src.indexOf('{width}') < 0) {
    return src;
  }

  if (/imageView/.test(query)) {
    if (!/interlace/.test(query)) {
      src = `${src}/interlace/1`;
    }
    if (!/webp/.test(query) && webp) {
      src = `${src}/format/webp`;
    } else if (!/format/.test(query) && /\.png$/i.test(imgName)) {
      src = `${src}/format/jpg`;
    }
  }
  return (src || '')
    .replace('http://', 'https://')
    .replace('{mode}', mode)
    .replace('{width}', width)
    .replace('{height}', height);
}