Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Image2HTML {
- constructor(blob, element = false) {
- this.blob = blob;
- this.element = element || document.body;
- }
- async render() {
- const data = await this.parseImage();
- const html = this.generateHTML(data);
- this.element.innerHTML = html;
- return this;
- }
- parseImage() {
- return new Promise(resolve => {
- const image = new Image();
- image.src = URL.createObjectURL(this.blob);
- image.onload = () => {
- const canvas = document.createElement('canvas');
- const ctx = canvas.getContext('2d');
- canvas.width = image.width;
- canvas.height = image.height;
- ctx.drawImage(image, 0, 0);
- const rgba = ctx.getImageData(0, 0, image.width, image.height).data;
- URL.revokeObjectURL(image.src);
- resolve({ width: canvas.width, height: canvas.height, rgba });
- }
- });
- }
- generateHTML(data) {
- let html = `<div style="width: ${data.width}px;height:${data.height}px;position:relative;>`;
- for (let i = 0; i < data.width * data.height; i++) {
- const rgba = data.rgba.slice(i * 4, (i * 4) + 4);
- rgba[rgba.length - 1] = rgba[rgba.length - 1] / 255;
- const color = `rgba(${rgba.join(', ')})`;
- let def = `width:1px;height:1px;display: inline-block;position:absolute;`;
- let x = i % data.width;
- if (x == 0 && i != 0) x = data.width;
- let y = Math.ceil(i / data.width);
- if (x == data.width) y -= 1;
- def += `left: ${x}px;top: ${y}px;`;
- html += `<span style="${def}background:${color};"></span>`;
- }
- html += `</div>`;
- return html;
- }
- }
- 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());
- await new Image2HTML(blob).render()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement