husq
2023-09-27 2c2bc8614c8ea0ce386369eb4924da1e6aa052d1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
 * 加载图片
 * @param url
 * @returns
 */
export function urlToImage (url: string) {
  return new Promise<HTMLImageElement>((resolve, reject) => {
    const image = new Image()
    image.src = url
    image.onload = () => { resolve(image) }
    image.onerror = () => { reject(new Error('image load error')) }
  })
}
 
export interface CompressImageData {
  blob: Blob | null;
  imageData: ImageData;
}
export function compressImage (imgToCompress: HTMLImageElement, targetWidth: number, targetHeight: number): Promise<CompressImageData> | undefined {
  // resizing the image
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  if (context) {
    const iWidth = imgToCompress.width
    const iHeight = imgToCompress.height
    const iRatio = iWidth / iHeight // 图像宽高比
    const tRatio = targetWidth / targetHeight // 目标宽高比
    let dw = targetWidth
    let dh = targetHeight
    let dx = 0
    let dy = 0
    if (iRatio > tRatio) {
      // 如果图像宽高比比目标宽高比要大,说明图像比目标尺寸更宽,这时候我们应该按照高度缩放比来进行缩放宽度
      dw = (targetHeight / iHeight) * iWidth
      // 宽度溢出,应该放在中间
      dx = -(dw - targetWidth) / 2
    } else {
      // 否则说明图像比目标尺寸更高,按照宽度缩放比来缩放高度
      dh = (targetWidth / iWidth) * iHeight
      // 高度溢出,应该放在中间
      dy = -(dh - targetHeight) / 2
    }
 
    canvas.width = targetWidth
    canvas.height = targetHeight
 
    context.drawImage(
      imgToCompress,
      dx,
      dy,
      dw,
      dh,
    )
 
    return new Promise<CompressImageData>((resolve) => {
      const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
 
      canvas.toBlob(blob => resolve({
        blob,
        imageData,
      }))
    })
  }
}
 
/**
 * 根据资源url下载文件
 * @param url
 * @param fileName
 */
export function download (url: string, fileName = ''): void {
  const aLink = document.createElement('a')
  aLink.style.display = 'none'
  aLink.download = fileName
  aLink.href = url
  document.body.appendChild(aLink)
  // 避免新开页面,闪烁
  // aLink.target = '_blank'
  aLink.click()
  document.body.removeChild(aLink)
  // aLink.remove()
}