Describes how to use JavaScript to create simple ASCII and Single Pole diagrams, ascii Single Pole

Source: Internet
Author: User

Describes how to use JavaScript to create simple ASCII and Single Pole diagrams, ascii Single Pole

ASCII chart

When executing various commands on the terminal, you will often see some "Images" displayed on the terminal, which are similar to a picture. In the near future, they are ASCII codes, which are roughly like this.


What we need to do today is to use JS to convert a given image into an "ASCII image" consisting of ASCII characters to see the final effect first. Assume that the image we have given is like this,


This is the result of code processing.I'mYasicThese 8 characters are used to indicate the approximate contour.


Single-level chart

The other image is a single pole image, that is, a black-and-white image, or the image you just created. The output is as follows:


Basic knowledge

The two graphs are relatively simple. You only need the following knowledge.

  • Canvas in HTML5
  • RGB values of pixels
  • Canvas APIs in JS

Create an ASCII chart

In general, most of the images we see in the computer are composed of pixels, and each pixel is composed of RGBA. In css, we often usergba(255, 255, 255, 255, 0)It is a set of RGBA values, that is, RGB primary colors and Alpha transparency. Of course, an image contains not only all the pixel data, but also some descriptive information, also known as the profile of the image. This part is smaller than several KB, and more than several hundred KB, it is the part that is often processed during image compression.

For each pixel in the image, as long as we change the value of the corresponding RGBA, the final image will change. The modified pixels and RGBA determine the final image style, which is also a mechanism used by many filters.

Based on the above theoretical knowledge, our ASCII graph creation idea is also available. An ASCII graph is actually a pixel in a graph. By calculating its RGBA value, it is divided into a given number of quantitative values.I'mYasicThese 8 characters are represented. Therefore, they must be divided into eight groups of values, each of which is represented by an ASCII character. In the end, they can form a complete ASCII image.

The next step is the specific code implementation.

Obtains the pixel information of an image.

In the Canvas APIgetImageData() We can obtain an object. The attribute of this object contains a one-dimensional array data. Each of the four elements of this one-dimensional array is a group that represents all the pixel information within the specified range in a canvas, the values are RED, GREEN, BLUE, and ALPHA in sequence. Therefore, we can first put the image into the canvas, and then call this method to get the pixel.

However, I am wondering why data is a one-dimensional array. Generally, the processed images are two-dimensional images. If two-dimensional arrays are used to represent pixel information, it is much easier to read and Process Code, it is easier to understand. You can even use a three-dimensional array to place RGBA information with a specific dimension.

The code for obtaining image pixel information is as follows:

var canvasContext = canvas.getContext("2d");canvasContext.drawImage(sourceImg, 0, 0);var imgData = canvasContext.getImageData(0 , 0, sourceImg.width, sourceImg.height);var imgDataArray = imgData.data;

The RGBA value of a pixel can be obtained in this way.

var r = imgDataArray[lineIndex];var g = imgDataArray[lineIndex + 1];var b = imgDataArray[lineIndex + 2];var a = imgDataArray[lineIndex + 3];

LineIndex is the benchmark variable that traverses each pixel.

Grayscale Images

Grayscale: gets the gray value of a pixel. Each pixel contains four types of information: RGBA. Therefore, we need to divide the RGBA values of all pixels into eight groups, the RGBA value of the corresponding pixel is Y = R = G = B. Here we do not consider transparency Alpha. Since the RGB value is equal, the pixel color is between the white and black gray, so this process is also called grayscale.

There are many grayscale algorithms. Here we adopt the simplest method, that is

Y = (R + G + B) * 1/3

The Code is as follows:

function rgb2gray(r, g, b) { return r * 0.333 + g * 0.333 + b * 0.333;}

Grayscale image quantification

After the grayscale image is roughly long, we can see that the colors have all become gray.


The next step is the key "quantization" process. That is to say, we should divide these gray-scale values into eight groups, and each group should be assigned an ASCII character as the mark. Of course, the ASCII characters selected must also be regular, in simple terms, the color ranges from deep to light, and the character ranges from complex to simple. The quantization process is to divide the range 0-into eight intervals and determine the intervals in which the gray value falls. The Code is as follows.

Because the number of pixels in the image is huge, the "binary decision" method can be used to increase the decision speed for efficiency.

function gray2asc(gray) { /*ASCII--I'mYasic*/ /*32 64 96 128 160 192 224 256*/ gray = 255 - gray; if (gray < 128){  if (gray < 64){   if (gray < 32){    return '\''   }   else {    return 'c'   }  }  else {   if (gray < 96){    return 'i'   }   else {    return 's'   }  } } else {  if (gray < 192){   if (gray < 160){    return 'I'   }   else {    return 'm'   }  }  else {   if (gray < 224){    return 'a'   }   else {    return 'Y'   }  } }}

Traversal and display

The process of converting a pixel to an ASCII code is explained above, and the next step is to traverse and display it.

Traversal

It is basically impossible to traverse all the pixels and convert them into ASCII codes, because the image computing workload increases a lot, so we compromise that the rows and columns of the pixel array are sampled at intervals, the final resolution of the displayed image will increase as the sampling interval decreases. In addition, note that the data array is a one-dimensional array, and every four elements are a group of RGBA data. The Code is as follows:

 var result = ""; var lineIndex = 0; for (var lineHeight = 0; lineHeight < sourceImg.height; lineHeight += 12){  var lineASC = "";  for (var lineFlag = 0; lineFlag < sourceImg.width; lineFlag += 5){   lineIndex = (lineHeight * sourceImg.width + lineFlag) * 4;   var r = imgDataArray[lineIndex];   var g = imgDataArray[lineIndex + 1];   var b = imgDataArray[lineIndex + 2];   lineASC += gray2asc(rgb2gray(r, g, b));  }  lineASC += '\n';  result += lineASC; }

Display

The final obtainedresult A string is the ASCII code to be displayed. However, it must be noted that if the text is displayed directly on the page, the ASCII image will be "distorted" due to the different character widths of each character. here we can use the Monospace font to ensure that the character width is consistent.

Create a polar chart

In fact, after reading the above part, we should know that the Single Pole graph is very easy to implement. We also need to obtain pixel information and make it grayscale, but it is only quantified as rgb (0, 0, 0) during quantification) and rgb (255,255,255.

 var canvasContext = targetCanvas.getContext("2d"); canvasContext.drawImage(sourceImg, 0, 0); var imgData = canvasContext.getImageData(0 , 0, sourceImg.width, sourceImg.height); var imgDataArray = imgData.data; for (var index = 0; index <= sourceImg.width * sourceImg.height * 4; index += 4){  var red = imgDataArray[index];  var green = imgDataArray[index + 1];  var blue = imgDataArray[index + 2];  var gray = rgb2gray(red, green, blue);  if (gray < 128){   imgData.data[index] = 0;   imgData.data[index + 1] = 0;   imgData.data[index + 2] = 0;  }  else {   imgData.data[index] = 255;   imgData.data[index + 1] = 255;   imgData.data[index + 2] = 255;  } } canvasContext.putImageData(imgData, 0, 0);

Don't forget to useputImageData Method: return the modified pixel information to the canvas for display.

Complete ASCII graph code

function rgb2gray(r, g, b) { return r * 0.333 + g * 0.333 + b * 0.333;}function gray2asc(gray) { /*ASCII--I'mYasic*/ /*32 64 96 128 160 192 224 256*/ gray = 255 - gray; if (gray < 128){  if (gray < 64){   if (gray < 32){    return '\''   }   else {    return 'c'   }  }  else {   if (gray < 96){    return 'i'   }   else {    return 's'   }  } } else {  if (gray < 192){   if (gray < 160){    return 'I'   }   else {    return 'm'   }  }  else {   if (gray < 224){    return 'a'   }   else {    return 'Y'   }  } }}var img2ASC = function (canvas, sourceImg) { console.log(sourceImg.width + " " + sourceImg.height); var canvasContext = canvas.getContext("2d"); canvasContext.drawImage(sourceImg, 0, 0); var imgData = canvasContext.getImageData(0 , 0, sourceImg.width, sourceImg.height); var imgDataArray = imgData.data; var result = ""; var lineIndex = 0; for (var lineHeight = 0; lineHeight < sourceImg.height; lineHeight += 12){  var lineASC = "";  for (var lineFlag = 0; lineFlag < sourceImg.width; lineFlag += 5){   lineIndex = (lineHeight * sourceImg.width + lineFlag) * 4;   var r = imgDataArray[lineIndex];   var g = imgDataArray[lineIndex + 1];   var b = imgDataArray[lineIndex + 2];   lineASC += gray2asc(rgb2gray(r, g, b));  }  lineASC += '\n';  result += lineASC; } document.getElementById("result").innerHTML = result;};

Complete code for a single pole chart

function rgb2gray(r, g, b) { return r * 0.333 + g * 0.333 + b * 0.333;}function gray2asc(gray) { /*ASCII--I'mYasic*/ /*32 64 96 128 160 192 224 256*/ if (gray < 128){  if (gray < 64){   if (gray < 32){    return '\''   }   else {    return 'c'   }  }  else {   if (gray < 96){    return 'i'   }   else {    return 's'   }  } } else {  if (gray < 192){   if (gray < 160){    return 'I'   }   else {    return 'm'   }  }  else {   if (gray < 224){    return 'a'   }   else {    return 'Y'   }  } }}var monoImg = function (targetCanvas, sourceImg) { targetCanvas.width = sourceImg.width; targetCanvas.height = sourceImg.height; var canvasContext = targetCanvas.getContext("2d"); canvasContext.drawImage(sourceImg, 0, 0); var imgData = canvasContext.getImageData(0 , 0, sourceImg.width, sourceImg.height); var imgDataArray = imgData.data; for (var index = 0; index <= sourceImg.width * sourceImg.height * 4; index += 4){  var red = imgDataArray[index];  var green = imgDataArray[index + 1];  var blue = imgDataArray[index + 2];  var gray = rgb2gray(red, green, blue);  if (gray < 128){   imgData.data[index] = 0;   imgData.data[index + 1] = 0;   imgData.data[index + 2] = 0;  }  else {   imgData.data[index] = 255;   imgData.data[index + 1] = 255;   imgData.data[index + 2] = 255;  } } canvasContext.putImageData(imgData, 0, 0);};

Summary

This blog focuses on using the Canvas API in JS for some simple pixel operations, but there are still a lot to be improved. For example, after a single pole chart is displayed, there will be noise in many places, that is, some eye-catching white points and black spots. You can "remove noise" in some ways and leave it for future writing! The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.