简体   繁体   中英

Algorithm to create a bitmap/canvas image from binary 1's and 0's to visually see the data in JavaScript?

Let's say I have 20,164 binary digits in a standard JavaScript string, for example:

var data = '101010101010101010101010100110001011010101101' ...

What I want to do is see a visual representation of these digits by converting it to a bitmap or perhaps HTML5 canvas image. So if I loop through all the bits and it comes across a 1 it will draw a black pixel, and a 0 the pixel will be white.

So I'm guessing I'll need a 142 x 142 pixel grid something which looks like this:

二进制数据位图

What's an algorithm or way to do this in JavaScript? All I need to do is display it on the web page so maybe creating a basic bitmap or canvas or SVG image will be fine.

Many thanks

You're exactly correct with the HTML5 canvas idea. You could try something like the following if you don't want to do base64 data.

Javascript (with no error checking):

var string = "1010101...";
var ctx = document.getElementById("canvas").getContext('2d');
ctx.fillStyle = "#FFF";  // Fill with white first
ctx.fillRect(0, 0, 142, 142);
ctx.fillStyle = "#000";
for (var i = 0; i < 142; i++) {  // Loop through each character
    for (var j = 0; j < 142; j++) {
        if (string[i*142+j] == '1')     // If the character is one,
            ctx.fillRect(i, j, 1, 1 );  // fill the pixel with black
    }
}

HTML:

<body>
    <canvas width=142 height=142 id="canvas"></canvas>
</body>

If you use this, you should make sure to check that the length of the string is the length you are expecting.

you can do something like

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.src ="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
image.onload = function() {
    ctx.drawImage(image, 0, 0);
};

You may also include the image directly in the HTML without using JS:

Example:

<img alt='' src='data:image/gif;base64,R0lGODlhBgASALMAAOfn5+rq6uvr6+zs7O7u7vHx8fPz8/b29vj4+P39/f///wAAAAAAAAAAAAAAAAAAACwAAAAABgASAAAIMAAVCBxIsKDBgwgTDkzAsKGAhxARSJx4oKJFAxgzFtjIkYDHjwNCigxAsiSAkygDAgA7'/>

But the image must be in a correct format: jpg, tiff, png, etc. not just as a bitmap. You may easily convert a bitmap to formats like BMP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM