| 72 | } |
| 73 | |
| 74 | export async function resizeImage( |
| 75 | dataURL: string, |
| 76 | maxSize: number |
| 77 | ): Promise<Image> { |
| 78 | const img = new Image() |
| 79 | const promise = new Promise<Image>((resolve, reject) => { |
| 80 | img.addEventListener('load', () => { |
| 81 | let { width, height } = img |
| 82 | if (width > maxSize || height > maxSize) { |
| 83 | if (width > height) { |
| 84 | height *= maxSize / width |
| 85 | width = maxSize |
| 86 | } else { |
| 87 | width *= maxSize / height |
| 88 | height = maxSize |
| 89 | } |
| 90 | } |
| 91 | const canvas = document.querySelector('#resizer') as HTMLCanvasElement |
| 92 | const ctx = canvas.getContext('2d') as CanvasRenderingContext2D |
| 93 | canvas.width = width |
| 94 | canvas.height = height |
| 95 | ctx.drawImage(img, 0, 0, width, height) |
| 96 | const resizedDataURL = canvas.toDataURL('image/jpeg') |
| 97 | resolve({ |
| 98 | url: resizedDataURL, |
| 99 | width, |
| 100 | height, |
| 101 | createdAt: new Date() |
| 102 | }) |
| 103 | }) |
| 104 | img.addEventListener('error', e => { |
| 105 | reject(new Error(`Failed to resize image: ${e.message}`)) |
| 106 | }) |
| 107 | }) |
| 108 | img.src = dataURL |
| 109 | return promise |
| 110 | } |
| 111 | |
| 112 | export const MOBILE_WIDTH = 580 |