aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/generativeFill/generativeFillUtils/ImageHandler.ts
blob: 8d32221bd284af75f03415117e9cb9342f28fcdb (plain)
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
204
205
206
207
208
209
210
211
212
213
import { RefObject } from 'react';
import { bgColor, canvasSize } from './generativeFillConstants';

export interface APISuccess {
    status: 'success';
    urls: string[];
}

export interface APIError {
    status: 'error';
    message: string;
}

export class ImageUtility {
    static canvasToBlob = (canvas: HTMLCanvasElement): Promise<Blob> => {
        return new Promise(resolve => {
            canvas.toBlob(blob => {
                if (blob) {
                    resolve(blob);
                }
            }, 'image/png');
        });
    };

    // given a square api image, get the cropped img
    static getCroppedImg = (img: HTMLImageElement, width: number, height: number): HTMLCanvasElement | undefined => {
        // Create a new canvas element
        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        if (ctx) {
            // Clear the canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            if (width < height) {
                // horizontal padding, x offset
                const xOffset = (canvasSize - width) / 2;
                console.log(xOffset);
                ctx.drawImage(img, xOffset, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
            } else {
                // vertical padding, y offset
                const yOffset = (canvasSize - height) / 2;
                ctx.drawImage(img, 0, yOffset, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
            }
            return canvas;
        }
    };

    static convertImageToCanvasDataURL = async (imageSrc: string, width: number, height: number): Promise<string> => {
        return new Promise<string>((resolve, reject) => {
            const img = new Image();
            img.onload = () => {
                const canvas = this.getCroppedImg(img, width, height);
                if (canvas) {
                    const dataUrl = canvas.toDataURL();
                    resolve(dataUrl);
                }
            };
            img.onerror = error => {
                reject(error);
            };
            img.src = imageSrc;
        });
    };

    static getEdit = async (imgBlob: Blob, maskBlob: Blob, prompt: string, n?: number): Promise<APISuccess | APIError> => {
        const apiUrl = 'https://api.openai.com/v1/images/edits';
        const fd = new FormData();
        fd.append('image', imgBlob, 'image.png');
        fd.append('mask', maskBlob, 'mask.png');
        fd.append('prompt', prompt);
        fd.append('size', '512x512');
        fd.append('n', n ? JSON.stringify(n) : '1');
        fd.append('response_format', 'b64_json');

        try {
            const res = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    Authorization: `Bearer ${process.env.OPENAI_KEY}`,
                },
                body: fd,
            });
            const data = await res.json();
            console.log(data.data);
            return {
                status: 'success',
                urls: (data.data as { b64_json: string }[]).map(data => `data:image/png;base64,${data.b64_json}`),
            };
        } catch (err) {
            console.log(err);
            return { status: 'error', message: 'API error.' };
        }
    };

    static mockGetEdit = async (mockSrc: string): Promise<APISuccess | APIError> => {
        return {
            status: 'success',
            urls: [mockSrc, mockSrc, mockSrc],
        };
    };

    static getCanvasContext = (canvasRef: RefObject<HTMLCanvasElement>): CanvasRenderingContext2D | null => {
        if (!canvasRef.current) return null;
        const ctx = canvasRef.current.getContext('2d');
        if (!ctx) return null;
        return ctx;
    };

    static downloadCanvas = (canvas: HTMLCanvasElement) => {
        const url = canvas.toDataURL();
        const downloadLink = document.createElement('a');
        downloadLink.href = url;
        downloadLink.download = 'canvas';

        downloadLink.click();
        downloadLink.remove();
    };

    static downloadImageCanvas = (imgUrl: string) => {
        const img = new Image();
        img.src = imgUrl;
        img.onload = () => {
            const canvas = document.createElement('canvas');
            canvas.width = canvasSize;
            canvas.height = canvasSize;
            const ctx = canvas.getContext('2d');
            ctx?.drawImage(img, 0, 0, canvasSize, canvasSize);

            this.downloadCanvas(canvas);
        };
    };

    static clearCanvas = (canvasRef: React.RefObject<HTMLCanvasElement>) => {
        const ctx = this.getCanvasContext(canvasRef);
        if (!ctx || !canvasRef.current) return;
        ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
    };

    static drawImgToCanvas = (img: HTMLImageElement, canvasRef: React.RefObject<HTMLCanvasElement>, width: number, height: number) => {
        const drawImg = (img: HTMLImageElement) => {
            const ctx = this.getCanvasContext(canvasRef);
            if (!ctx) return;
            ctx.globalCompositeOperation = 'source-over';
            ctx.clearRect(0, 0, width, height);
            ctx.drawImage(img, 0, 0, width, height);
        };

        if (img.complete) {
            drawImg(img);
        } else {
            console.log('loading image');
            img.onload = () => {
                drawImg(img);
            };
        }
    };

    // The image must be loaded!
    static getCanvasMask = (srcCanvas: HTMLCanvasElement): HTMLCanvasElement | undefined => {
        const canvas = document.createElement('canvas');
        canvas.width = canvasSize;
        canvas.height = canvasSize;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;
        ctx?.clearRect(0, 0, canvasSize, canvasSize);
        ctx.fillStyle = bgColor;
        ctx.fillRect(0, 0, canvasSize, canvasSize);

        // extract and set padding data
        if (srcCanvas.height > srcCanvas.width) {
            // horizontal padding, x offset
            const xOffset = (canvasSize - srcCanvas.width) / 2;
            ctx?.clearRect(xOffset, 0, srcCanvas.width, srcCanvas.height);
            ctx.drawImage(srcCanvas, xOffset, 0, srcCanvas.width, srcCanvas.height);
        } else {
            // vertical padding, y offset
            const yOffset = (canvasSize - srcCanvas.height) / 2;
            ctx?.clearRect(0, yOffset, srcCanvas.width, srcCanvas.height);
            ctx.drawImage(srcCanvas, 0, yOffset, srcCanvas.width, srcCanvas.height);
        }
        return canvas;
    };

    // The image must be loaded!
    static getCanvasImg = (img: HTMLImageElement): HTMLCanvasElement | undefined => {
        const canvas = document.createElement('canvas');
        canvas.width = canvasSize;
        canvas.height = canvasSize;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;
        // fix scaling
        const scale = Math.min(canvasSize / img.width, canvasSize / img.height);
        const width = img.width * scale;
        const height = img.height * scale;
        ctx?.clearRect(0, 0, canvasSize, canvasSize);
        ctx.fillStyle = bgColor;
        ctx.fillRect(0, 0, canvasSize, canvasSize);

        // extract and set padding data
        if (img.naturalHeight > img.naturalWidth) {
            // horizontal padding, x offset
            const xOffset = (canvasSize - width) / 2;

            ctx.drawImage(img, xOffset, 0, width, height);
        } else {
            // vertical padding, y offset
            const yOffset = (canvasSize - height) / 2;
            ctx.drawImage(img, 0, yOffset, width, height);
        }
        return canvas;
    };
}