Advertisement
KoctrX

Untitled

Nov 15th, 2023
722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Image2HTML {
  2.     constructor(blob, element = false) {
  3.         this.blob = blob;
  4.         this.element = element || document.body;
  5.     }
  6.  
  7.     async render() {
  8.         const data = await this.parseImage();
  9.         const html = this.generateHTML(data);
  10.  
  11.         this.element.innerHTML = html;
  12.         return this;
  13.     }
  14.  
  15.     parseImage() {
  16.         return new Promise(resolve => {
  17.             const image = new Image();
  18.             image.src = URL.createObjectURL(this.blob);
  19.  
  20.             image.onload = () => {
  21.                 const canvas = document.createElement('canvas');
  22.                 const ctx = canvas.getContext('2d');
  23.  
  24.                 canvas.width = image.width;
  25.                 canvas.height = image.height;
  26.  
  27.                 ctx.drawImage(image, 0, 0);
  28.                 const rgba = ctx.getImageData(0, 0, image.width, image.height).data;
  29.  
  30.                 URL.revokeObjectURL(image.src);
  31.                 resolve({ width: canvas.width, height: canvas.height, rgba });
  32.             }
  33.         });
  34.     }
  35.  
  36.     generateHTML(data) {
  37.         let html = `<div style="width: ${data.width}px;height:${data.height}px;position:relative;>`;
  38.  
  39.        for (let i = 0; i < data.width * data.height; i++) {
  40.            const rgba = data.rgba.slice(i * 4, (i * 4) + 4);
  41.            rgba[rgba.length - 1] = rgba[rgba.length - 1] / 255;
  42.            const color = `rgba(${rgba.join(', ')})`;
  43.            let def = `width:1px;height:1px;display: inline-block;position:absolute;`;
  44.            let x = i % data.width;
  45.            if (x == 0 && i != 0) x = data.width;
  46.            let y = Math.ceil(i / data.width);
  47.            if (x == data.width) y -= 1;
  48.  
  49.            def += `left: ${x}px;top: ${y}px;`;
  50.            html += `<span style="${def}background:${color};"></span>`;
  51.        }
  52.  
  53.        html += `</div>`;
  54.        return html;
  55.    }
  56. }
  57.  
  58. blob = await fetch('https://storage.googleapis.com/turbo-math.appspot.com/user-assets/gzMWmegNKSUlh64nFjBAIuqhqGr2/04-23-2023/image-to-image/image-to-image__5f419cc4305219bba97ae735b799a45d_1682284222619_1_1682284234.png').then(res => res.blob());
  59. await new Image2HTML(blob).render()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement