DEV Community

Gustavo Flores
Gustavo Flores

Posted on

27 3

Convert an Image to HTML pixel by pixel

Hi!
This is a tutorial to convert an image to HTML pixel by pixel, with this you can analyze your image :)

first, you need some HTML

<!-- canvas need to be hidden, here you will load your image and take information about it -->
<canvas
    id="canvas"
    style="visibility: hidden;"
></canvas>
<!-- here you will print your matrix of span tags, each of them with a single color -->
<div
    id="final-image"
    style="line-height: 7px;letter-spacing: -3px;"
></div>
Enter fullscreen mode Exit fullscreen mode

now some javascript


const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const imgUrl = "https://images.unsplash.com/photo-1549740425-5e9ed4d8cd34?ixid=MXwxMjA3fDB8MHxjb2xsZWN0aW9uLXBhZ2V8MXwzOTU0NTB8fGVufDB8fHw%3D&ixlib=rb-1.2.1&w=1000&q=80";
const img = new Image();
const imgWidth = 100;

let html = "";
img.crossOrigin = "Anonymous";
img.onload = function() {
    canvas.width = imgWidth;
    canvas.height = (this.height * canvas.width) / this.width;
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    for (let i = 0; i < canvas.height; i++) {
        for (let j = 0; j < canvas.width; j++) {
            add(ctx.getImageData(j, i, 1, 1).data);
        }
        html += "<br />";
    }
    document.getElementById("final-image").innerHTML = html;
    canvas.parentNode.removeChild(canvas);
};

img.src = imgUrl;

function add(c) {
    html += `<span style="color: rgb(${c[0]}, ${c[1]}, ${c[2]});">&#9632;</span>`;
}
Enter fullscreen mode Exit fullscreen mode

with this code, you can print your image on text

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
normadye profile image
NormaDye

Get an image data (convert it into an array of pixels so I could edit it) and then return the edited array back from the pixels editing function so that I could use these edited values to draw an edited image. love binding spell

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs