File size: 1,940 Bytes
2bc6d22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createCanvas, imageDataToCanvas } from './canvas';

interface ResizeOptions {
  width?: number;
  height?: number;
  maintainAspectRatio?: boolean;
}

export function calculateDimensions(
  originalWidth: number,
  originalHeight: number,
  options: ResizeOptions
): { width: number; height: number } {
  const { width: targetWidth = 0, height: targetHeight = 0, maintainAspectRatio = true } = options;

  if (!targetWidth && !targetHeight) {
    return { width: originalWidth, height: originalHeight };
  }

  let finalWidth = targetWidth || originalWidth;
  let finalHeight = targetHeight || originalHeight;

  if (maintainAspectRatio) {
    const aspectRatio = originalWidth / originalHeight;

    if (targetWidth && !targetHeight) {
      finalWidth = targetWidth;
      finalHeight = Math.round(targetWidth / aspectRatio);
    } else if (!targetWidth && targetHeight) {
      finalHeight = targetHeight;
      finalWidth = Math.round(targetHeight * aspectRatio);
    } else {
      const widthRatio = targetWidth / originalWidth;
      const heightRatio = targetHeight / originalHeight;
      const ratio = Math.min(widthRatio, heightRatio);

      finalWidth = Math.round(originalWidth * ratio);
      finalHeight = Math.round(originalHeight * ratio);
    }
  }

  return {
    width: Math.max(1, finalWidth),
    height: Math.max(1, finalHeight),
  };
}

export function resizeImage(imageData: ImageData, options: ResizeOptions): ImageData {
  const sourceCanvas = imageDataToCanvas(imageData);
  
  const { width, height } = calculateDimensions(
    imageData.width,
    imageData.height,
    options
  );

  const destCanvas = createCanvas(width, height);
  const ctx = destCanvas.getContext('2d')!;

  // Use better image scaling algorithm
  ctx.imageSmoothingEnabled = true;
  ctx.imageSmoothingQuality = 'high';
  
  ctx.drawImage(sourceCanvas, 0, 0, width, height);
  
  return ctx.getImageData(0, 0, width, height);
}