DEV Community

Gustavo Flores
Gustavo Flores

Posted on

Convert an Image to HTML pixel by pixel

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 -->
    style="visibility: hidden;"
<!-- here you will print your matrix of span tags, each of them with a single color -->
    style="line-height: 7px;letter-spacing: -3px;"
Enter fullscreen mode Exit fullscreen mode

now some javascript

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const imgUrl = "";
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;

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

Top comments (1)

normadye profile image

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