Skip to content

Instantly share code, notes, and snippets.

@Sraw
Last active December 28, 2017 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sraw/c4330224572927a7a9a5f3a55a655a0a to your computer and use it in GitHub Desktop.
Save Sraw/c4330224572927a7a9a5f3a55a655a0a to your computer and use it in GitHub Desktop.
Use plain javascript to generate bmp file.
function drawArray(arr) {
/*
Thanks original author @vukicevic
Usage:
Pass a two-dimensional arrary.
The first dimonsion is rows, the second one is columns.
Note that in columns, each pixel is represented by four nums as BGRA, so the columns' length is four times as image's length.
return image's base64 code.
*/
var offset, height, width, size, data, image;
function bytes2(num) {
return String.fromCharCode(num & 0xff, (num >> 8) & 0xff);
}
function bytes4(num) {
return String.fromCharCode(num & 0xff, (num >> 8) & 0xff, (num >> 16) & 0xff, (num >> 24) & 0xff);
}
offset = 54;
height = arr.length;
width = Math.floor(arr[0].length / 4);
size = height * width;
//BMP Header
data = 'BM'; // ID field
data += bytes4(offset + size); // BMP size
data += bytes4(0); // unused
data += bytes4(offset); // pixel data offset
//DIB Header
data += bytes4(40); // DIB header length
data += bytes4(width); // image width
data += bytes4(height); // image height
data += bytes2(1); // colour panes
data += bytes2(32); // bits per pixel
data += bytes4(0); // compression method
data += bytes4(size); // size of the raw data
data += bytes4(0); // horizontal print resolution
data += bytes4(0); // vertical print resolution
data += bytes4(0); // colour palette, 0 == 2^n
data += bytes4(0); // important colours
//Pixel data
for (var h_pixel = height - 1; h_pixel >= 0; h_pixel--) {
data += String.fromCharCode.apply(null, arr[h_pixel]);
}
//Image element
image = 'data:image/bmp;base64,' + btoa(data);
return image;
}
// test case, a random 200x200 image.
for (var a = [], i = 0; i < 200; i++) {
for (var b = [], j = 0; j < 800; j++) {
b[j] = Math.floor(Math.random() * 256);
}
a[i] = b;
}
drawArray(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment