File size: 2,318 Bytes
3dabe4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
class ForgeCoupleImageLoader {

    static #maxDim = 1024;

    /** @param {string} filepath @param {method} callback */
    static #path2url(filepath, callback) {
        const img = new Image();

        img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            var width = img.width;
            var height = img.height;

            while (width > this.#maxDim || height > this.#maxDim) {
                width = parseInt(width / 2);
                height = parseInt(height / 2);
            }

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

            ctx.drawImage(img, 0, 0, width, height);
            const resizedDataUrl = canvas.toDataURL('image/jpeg');

            callback(resizedDataUrl);
        };

        img.src = filepath;
    }

    /** @param {Element} image @param {Element[]} btns */
    static setup(image, btns) {

        const [load, load_i2i, clear] = (btns.length === 3) ? btns : [btns[0], null, btns[1]];

        const img_upload = document.createElement("input");
        img_upload.setAttribute("type", "file");
        img_upload.setAttribute("accept", "image/*");

        load.onclick = () => { img_upload.click(); };

        img_upload.onchange = (event) => {
            const file = event.target.files[0];

            if (file != null) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.#path2url(e.target.result, (new_src) => {
                        image.style.backgroundImage = `url("${new_src}")`;
                    });
                };
                reader.readAsDataURL(file);
            }
        };

        if (load_i2i != null) {
            load_i2i.onclick = () => {
                const src = document.getElementById("img2img_image").querySelector("img")?.src;
                if (src != null) {
                    this.#path2url(src, (new_src) => {
                        image.style.backgroundImage = `url("${new_src}")`;
                    });
                }
            };
        }

        clear.onclick = () => { image.style.backgroundImage = "none"; };

        image.parentElement.appendChild(img_upload);
        img_upload.style.display = "none";

    }

}