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

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

  if (minScale && width / height < minScale) {
    height = width / minScale;
  }
  if (width === 1) {
    width = maxWidth;
  }
  if (height === 1) {
    height = maxWidth;
  }
  return {width, height: Math.round(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);
}