|
| 1 | +import type { OriginalImageMetadata } from "../types.ts" |
| 2 | + |
| 3 | +const MAX_DIMENSION = 2000 |
| 4 | + |
| 5 | +export const scaleImage = async (originalImage: OriginalImageMetadata): Promise<ImageData> => { |
| 6 | + const { scaledWidth, scaledHeight } = calculateScaledDimensions({ |
| 7 | + width: originalImage.width, |
| 8 | + height: originalImage.height, |
| 9 | + }) |
| 10 | + |
| 11 | + const canvas = createOffscreenCanvas(scaledWidth, scaledHeight) |
| 12 | + const context = getCanvasContext(canvas) |
| 13 | + |
| 14 | + await drawImageToCanvas({ context, dataUrl: originalImage.dataUrl, scaledWidth, scaledHeight }) |
| 15 | + |
| 16 | + return context.getImageData(0, 0, scaledWidth, scaledHeight) |
| 17 | +} |
| 18 | + |
| 19 | +const calculateScaledDimensions = ({ width, height }: { width: number; height: number }): { scaledWidth: number; scaledHeight: number } => { |
| 20 | + if (width <= MAX_DIMENSION && height <= MAX_DIMENSION) { |
| 21 | + return { scaledWidth: width, scaledHeight: height } |
| 22 | + } |
| 23 | + |
| 24 | + const scale = Math.min(MAX_DIMENSION / width, MAX_DIMENSION / height) |
| 25 | + |
| 26 | + return { |
| 27 | + scaledWidth: Math.round(width * scale), |
| 28 | + scaledHeight: Math.round(height * scale), |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +const createOffscreenCanvas = (width: number, height: number): HTMLCanvasElement => { |
| 33 | + const canvas = document.createElement("canvas") |
| 34 | + canvas.width = width |
| 35 | + canvas.height = height |
| 36 | + return canvas |
| 37 | +} |
| 38 | + |
| 39 | +const getCanvasContext = (canvas: HTMLCanvasElement): CanvasRenderingContext2D => { |
| 40 | + const context = canvas.getContext("2d") |
| 41 | + if (!context) { |
| 42 | + throw new Error("Failed to get canvas 2D context") |
| 43 | + } |
| 44 | + return context |
| 45 | +} |
| 46 | + |
| 47 | +const drawImageToCanvas = ({ context, dataUrl, scaledWidth, scaledHeight }: { context: CanvasRenderingContext2D; dataUrl: string; scaledWidth: number; scaledHeight: number }): Promise<void> => { |
| 48 | + return new Promise((resolve, reject) => { |
| 49 | + const image = new Image() |
| 50 | + |
| 51 | + image.onload = () => { |
| 52 | + context.drawImage(image, 0, 0, scaledWidth, scaledHeight) |
| 53 | + resolve() |
| 54 | + } |
| 55 | + |
| 56 | + image.onerror = () => { |
| 57 | + reject(new Error("Failed to load image for extraction")) |
| 58 | + } |
| 59 | + |
| 60 | + image.src = dataUrl |
| 61 | + }) |
| 62 | +} |
0 commit comments