| 142 | } |
| 143 | |
| 144 | export function rotateImgWithCanvas(image: HTMLImageElement, degrees: number): Promise<Blob> { |
| 145 | return new Promise((resolve, reject) => { |
| 146 | const canvas = document.createElement('canvas') |
| 147 | const ctx = canvas.getContext('2d') |
| 148 | |
| 149 | if (!ctx || !image.height || !image.width) return |
| 150 | const horizontal = [-270, -90, 90, 270] |
| 151 | if (horizontal.includes(degrees)) { |
| 152 | canvas.width = image.naturalHeight || 0 |
| 153 | canvas.height = image.naturalWidth || 0 |
| 154 | } else { |
| 155 | canvas.width = image.naturalWidth || 0 |
| 156 | canvas.height = image.naturalHeight || 0 |
| 157 | } |
| 158 | ctx.translate(canvas.width / 2, canvas.height / 2) |
| 159 | ctx.rotate((degrees * Math.PI) / 180) |
| 160 | ctx.drawImage(image, -image.naturalWidth / 2, -image.naturalHeight / 2) |
| 161 | canvas.toBlob(blob => { |
| 162 | blob ? resolve(blob) : reject('blob is null') |
| 163 | }, 'image/jpeg') |
| 164 | }) |
| 165 | } |