File size: 5,757 Bytes
4e1096a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/**
 * Process book cover for Discord Rich Presence:
 * - Fit to 512x512 with transparent background
 * - Add Readest icon overlay at bottom right (10px padding)
 * - Return as JPEG blob
 */
export async function processDiscordCover(coverUrl: string, iconUrl: string): Promise<Blob> {
  const SIZE = 512;
  const ICON_WIDTH = 224;
  const ICON_HEIGHT = 182;
  const PADDING = 10;

  try {
    const coverResponse = await fetch(coverUrl);
    const coverBlob = await coverResponse.blob();
    const coverImg = new Image();
    coverImg.crossOrigin = 'anonymous';

    const iconResponse = await fetch(iconUrl);
    const iconBlob = await iconResponse.blob();
    const iconImg = new Image();
    iconImg.crossOrigin = 'anonymous';

    return new Promise((resolve, reject) => {
      let coverLoaded = false;
      let iconLoaded = false;

      const checkBothLoaded = () => {
        if (!coverLoaded || !iconLoaded) return;

        try {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');

          if (!ctx) {
            reject(new Error('Failed to get canvas context'));
            return;
          }

          canvas.width = SIZE;
          canvas.height = SIZE;

          // Calculate cover dimensions to fit in 512x512
          const aspectRatio = coverImg.width / coverImg.height;
          let drawWidth, drawHeight, offsetX, offsetY;

          if (aspectRatio > 1) {
            // Wider than tall
            drawWidth = SIZE;
            drawHeight = SIZE / aspectRatio;
            offsetX = 0;
            offsetY = (SIZE - drawHeight) / 2;
          } else {
            // Taller than wide
            drawHeight = SIZE;
            drawWidth = SIZE * aspectRatio;
            offsetX = (SIZE - drawWidth) / 2;
            offsetY = 0;
          }

          // Draw cover image centered
          ctx.imageSmoothingEnabled = true;
          ctx.imageSmoothingQuality = 'high';
          ctx.drawImage(coverImg, offsetX, offsetY, drawWidth, drawHeight);

          // Draw icon at bottom right
          ctx.drawImage(
            iconImg,
            SIZE - ICON_WIDTH - PADDING,
            SIZE - ICON_HEIGHT - PADDING,
            ICON_WIDTH,
            ICON_HEIGHT,
          );

          // Convert to JPEG blob
          canvas.toBlob(
            (blob) => {
              if (blob) {
                resolve(blob);
              } else {
                reject(new Error('Failed to create blob'));
              }
            },
            'image/jpeg',
            0.9,
          );
        } catch (error) {
          reject(new Error(`Failed to process cover: ${error}`));
        }
      };

      coverImg.onload = () => {
        coverLoaded = true;
        checkBothLoaded();
      };

      iconImg.onload = () => {
        iconLoaded = true;
        checkBothLoaded();
      };

      coverImg.onerror = () => reject(new Error('Failed to load cover image'));
      iconImg.onerror = () => reject(new Error('Failed to load icon image'));

      const coverObjectUrl = URL.createObjectURL(coverBlob);
      const iconObjectUrl = URL.createObjectURL(iconBlob);

      coverImg.src = coverObjectUrl;
      iconImg.src = iconObjectUrl;

      coverImg.onload = function () {
        URL.revokeObjectURL(coverObjectUrl);
        coverLoaded = true;
        checkBothLoaded();
      };

      iconImg.onload = function () {
        URL.revokeObjectURL(iconObjectUrl);
        iconLoaded = true;
        checkBothLoaded();
      };
    });
  } catch (error) {
    console.error('Error processing Discord cover:', error);
    throw error;
  }
}

export async function fetchImageAsBase64(
  url: string,
  options: {
    targetWidth?: number;
    format?: 'image/jpeg' | 'image/png' | 'image/webp';
    quality?: number;
  } = {},
): Promise<string> {
  const { targetWidth = 256, format = 'image/jpeg', quality = 0.85 } = options;

  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Failed to fetch image: ${response.status} ${response.statusText}`);
    }
    const blob = await response.blob();

    const img = new Image();
    img.crossOrigin = 'anonymous';

    return new Promise((resolve, reject) => {
      img.onload = () => {
        try {
          const aspectRatio = img.height / img.width;
          const newWidth = targetWidth;
          const newHeight = Math.round(newWidth * aspectRatio);

          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');

          if (!ctx) {
            reject(new Error('Failed to get canvas context'));
            return;
          }

          canvas.width = newWidth;
          canvas.height = newHeight;

          ctx.imageSmoothingEnabled = true;
          ctx.imageSmoothingQuality = 'high';

          ctx.drawImage(img, 0, 0, newWidth, newHeight);

          const base64 = canvas.toDataURL(format, quality);
          resolve(base64);
        } catch (error) {
          reject(new Error(`Failed to scale image: ${error}`));
        }
      };

      img.onerror = () => reject(new Error('Failed to load image for scaling'));

      const objectUrl = URL.createObjectURL(blob);
      img.src = objectUrl;

      const cleanup = () => URL.revokeObjectURL(objectUrl);
      const originalOnload = img.onload;
      const originalOnerror = img.onerror;

      img.onload = function (ev) {
        cleanup();
        if (originalOnload) originalOnload.call(this, ev);
      };

      img.onerror = function (ev) {
        cleanup();
        if (originalOnerror) originalOnerror.call(this, ev);
      };
    });
  } catch (error) {
    console.error('Error fetching and encoding image:', error);
    throw error;
  }
}