forked from noopkat/png-to-lcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpng-to-lcd.js
99 lines (79 loc) · 2.54 KB
/
png-to-lcd.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* png-to-lcd
* exports framebuffer for use with common OLED displays
*/
var floydSteinberg = require('floyd-steinberg');
var pngparse = require('pngparse');
module.exports = png_to_lcd;
// pngparse doesn't quite have the correct object setup for pixel data
function createImageData(image) {
var buf = new Buffer(image.width * image.height * 4);
var l = image.data.length;
var pos = 0;
for (var y = 0; y < image.height; y++) {
for (var x = 0; x < image.width; x++) {
buf.writeUInt32BE(image.getPixel(x, y), pos);
pos += 4;
}
}
image.data = buf;
return image;
}
function png_to_lcd(filename, dither, callback) {
// parse png file passed in
pngparse.parseFile(filename, function(err, img) {
if (err) {
return callback(err);
}
// post process pixel data returned
var pimage = createImageData(img);
var pixels = pimage.data,
pixelsLen = pixels.length,
height = pimage.height,
width = pimage.width,
alpha = pimage.hasAlphaChannel,
threshold = 120,
unpackedBuffer = [],
depth = 4;
// create a new buffer that will be filled with pixel bytes (8 bits per) and then returned
var buffer = new Buffer((width * height) / 8);
buffer.fill(0x00);
// if dithering is preferred, run this on the pixel data first to transform RGB vals
if (dither) {
floydSteinberg(pimage);
}
// filter pixels to create monochrome image data
for (var i = 0; i < pixelsLen; i += depth) {
// just take the red value
var pixelVal = pixels[i + 1] = pixels[i + 2] = pixels[i];
// do threshold for determining on and off pixel vals
if (pixelVal > threshold) {
pixelVal = 1;
} else {
pixelVal = 0;
}
// push to unpacked buffer list
unpackedBuffer[i/depth] = pixelVal;
}
// time to pack the buffer
for (var i = 0; i < unpackedBuffer.length; i++) {
// math
var x = Math.floor(i % width);
var y = Math.floor(i / width);
// create a new byte, set up page position
var byte = 0,
page = Math.floor(y / 8),
pageShift = 0x01 << (y - 8 * page);
// is the first page? Just assign byte pos to x value, otherwise add rows to it too
(page === 0) ? byte = x : byte = x + width * page;
if (unpackedBuffer[i] === 0) {
// 'off' pixel
buffer[byte] &= ~pageShift;
} else {
// 'on' pixel
buffer[byte] |= pageShift;
}
}
callback(err, buffer);
});
}