Blame view

apps/utils/image-handler.js 1.13 KB
陈峰 authored
1
const MAX_WIDTH = 1000;
陈峰 authored
2
yyq authored
3
export function getArticleImageSize({width, height, minScale = 0.75, maxWidth = MAX_WIDTH}) {
陈峰 authored
4 5
  width = +width;
  height = +height;
yyq authored
6 7 8
  if (width > maxWidth) {
    height = height / (width / maxWidth);
    width = maxWidth;
陈峰 authored
9 10
  }
yyq authored
11 12
  if (minScale && width / height < minScale) {
    height = width / minScale;
陈峰 authored
13 14
  }
  if (width === 1) {
陈峰 authored
15
    width = maxWidth;
陈峰 authored
16 17
  }
  if (height === 1) {
陈峰 authored
18
    height = maxWidth;
陈峰 authored
19
  }
yyq authored
20
  return {width, height: Math.round(height)};
陈峰 authored
21
}
陈峰 authored
22 23 24 25

export function processImage(src, mode, width, height, webp) {
  let splits = (src || '').split('?');
  const imgName = splits[0] || '';
ityuany authored
26
陈峰 authored
27 28
  let query = splits[1] || '';
yyq authored
29
  if (!src || src.indexOf('{width}') < 0) {
陈峰 authored
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    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);
}