Hand-in-hand teaching you how to transfer pictures to ASCII codes

Keywords: Javascript ascii

Design sketch

Basic thinking

  1. The most important thing is to get the value of rgb.

  2. Converting each pixel from rgb to gray level image, i.e. 0-255

  3. Grading 0-255, converting each level of pixels into ascii code, completes

Realization

Step 1: Get Pixel Information

Upon review, this requirement can be fulfilled using canvas's getImage Data method, as follows

<canvas id="canvas"></canvas>
<script>
    var canvas=document.getElementById("canvas");
    var context=canvas.getContext("2d");
    canvas.width=800;
    canvas.height=800;
    context.rect(0,0,800,800);
    context.fillStyle="red";
    context.fill();

    console.log(context.getImageData(0,0,800,800))
</script>

The above code refers to paving the canvas with red background color, and using getImageData() method to output each pixel of the entire canvas 800*800. In the console we can see the results of console:

We see a length of 256,000,000 and our width * height is 640,000. What's the matter? Isn't a pixel corresponding to one of getImageData()? We take 2560000/640000 and get a result value of 4, so we can preliminarily guess that in getImageData(), each pixel corresponds to four bits. Keep looking down

From the figure, we can see that 0123 is a cycle, and here our pixels are red. According to r (red) g (green) B (black), the red r G B should be (255, 0, 0), so 0-3 corresponds to the three colors of r G b, and the fourth value should refer to a (transparency).

Above, we have completed our preliminary understanding of getImageData().

Extension: Use getImageData() for reverse mapping

First, inversion means that every rgb value of each pixel is subtracted from 255 (the value of alpha does not change). After subtraction, the value is composed of images again. At this time, the new image is our inverted image.

The methods are as follows:

<canvas id="canvas"></canvas>
<script>
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    canvas.width = 800;
    canvas.height = 800;
    var img = new Image();
    img.src = "love.png";
    img.onload =function(){
        invert(this);
    };
    //    rgba array of pixels
    function invert(img) {
        context.drawImage(img,0,0);
        //Get an array of image objects and element points
        var img1 = context.getImageData(0, 0, 800, 800);
        var data = img1.data;
        //Reverse rgba
        for (var i = 0, len = data.length; i < len; i += 4) {
            data[i]=255-data[i];
            data[i+1]=255-data[i+1];
            data[i+2]=255-data[i+2];
        }
        context.putImageData(img1, 0, 0);
    }
</script>

The key point of this code is to get the image object and the data pixel data of the object. After modifying the data on the original object, the modified image object is assigned to canvas by putImageData method.

The results are as follows:

Original graph

Design sketch

If we can do inversion map, then we can also think about the next question. In fact, many of the filter effects we usually see are essentially changing the rgba value of the pixels, but the rgba algorithm of different filter effects is different, as we do now, the inversion effect can also be considered as one of the filters.

Step 2: Turn grayscale image

Gray Scale Image or Grey Scale Image, also known as Gray Scale Graph. The relationship between white and black is divided into several grades according to logarithm, which is called gray level. The gray scale is divided into 256 orders. The image represented by gray level is called gray level image.

Simply put, grayscale image is what we usually call black-and-white image. There are several algorithms for converting ordinary image into grayscale image.

1. Floating-point algorithm: Gray=R0.3+G0.59+B*0.11

2. Integer method: Gray=(R30+G59+B*11)/100

3. Displacement method: Gray = (R76+G151+B*28)> 8;

4. Average method: Gray=(R+G+B)/3;

5. Green only: Gray=G;

With our experience of inversion image above, this gray image conversion is actually very simple, the code is as follows:

//Conversion Grayscale Map
    for (var i = 0, len = data.length; i < len; i += 4) {
        var avg=(data[i]+data[i+1]+data[i+2])/3;
        data[i]=avg;
        data[i+1]=avg;
        data[i+2]=avg;
    }

Design sketch:

Step 3: Hierarchical conversion to character representation

The next step is to convert the characters into characters. Firstly, the characters are divided into 15 levels, i.e. 0-14, followed by

var arr=["M","N","H","Q","$","O","C","?","7",">","!",":","–",";","."];

To convert 0-255 to 0-14, the result of Math.floor(255/18) `is 14. The method is as follows:

var avg=(data[i]+data[i+1]+data[i+2])/3;
var num=Math.floor(avg/18);

So the basic code is as follows (note the method of line breaking):

function invert(img) {
    context.drawImage(img,0,0);
    //Get an array of image objects and element points
    var img1 = context.getImageData(0, 0, 300, 300);
    var data = img1.data;
    //Conversion Grayscale Map
    var arr=["M","N","H","Q","$","O","C","?","7",">","!",":","–",";","."];
    var result=[];
    for (var i = 0, len = data.length; i < len; i += 8) {
        var avg=(data[i]+data[i+1]+data[i+2])/3;
        var num=Math.floor(avg/18);
        result.push(arr[num]);
        if(i%1200==0&&i!=0){
            result.push("<br>")
        }
    }
    opt.innerHTML=result.join();
    document.body.appendChild(opt);
}

Posted by Jas on Sat, 20 Apr 2019 01:45:34 -0700