download.ts 2.3 KB

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