Skip to content

Instantly share code, notes, and snippets.

@tmpvar
Last active August 29, 2015 14:02
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 tmpvar/a4816d71e5bfba8c06ee to your computer and use it in GitHub Desktop.
Save tmpvar/a4816d71e5bfba8c06ee to your computer and use it in GitHub Desktop.
bitmap2gcode experiment
var context2d = require('context2d');
var Image = require('htmlimage');
var args = require('yargs')(process.argv.slice(2)).argv;
var img = new Image();
console.log(args);
if (!args.url) {
console.log('usage: node bitmap2gcode.js --url="http|file://path/to/thingy.png --dpi=90 --depth=5 --depthPerPass')
}
img.onload = function() {
var imageData = img.imageData;
var max = 0;
var size = imageData.width*imageData.height;
var f32a = new Float32Array(size);
var source = imageData.data;
var pixelDepthMax = (3*255);
for (var i = 0; i<size; i++) {
// collect a ratio of depth so we can apply it to the incoming depth in mm
var r = source[i*4] * (args.rmult || 1)
var g = source[i*4 + 1] * (args.gmult || 1)
var b = source[i*4 + 2] * (args.bmult || 1)
f32a[i] = 1 - (Math.min(r+g+b, pixelDepthMax) / pixelDepthMax);
if (max < f32a[i]) {
max = f32a[i];
}
}
var w = imageData.width;
var h = imageData.height;
var move = function(x, y, z) {
var obj = {x:x, y:y, z:z};
console.log('G1' + Object.keys(obj).filter(function(k) {
if (typeof obj[k] !== 'undefined' && obj[k] !== null) {
return true;
}
return false;
}).map(function(k) {
return k + Number(obj[k]).toFixed(3);
}).join(''));
}
args.dpm = args.dpm || 1;
move(null, null, .5);
for (var waterline = -args.depthPerPass; waterline>=args.depth; waterline-=args.depthPerPass) {
for (var x=0; x<w; x+=args.dpm) {
move(x / args.dpm);
move(null, null, 0);
for (var y = 0; y<h; y++) {
var v = Math.max(waterline, f32a[y*h + x] * args.depth);
if (typeof args.smooth !== 'undefined') {
move(null, y / args.dpm, v);
} else {
move(null, null, v);
move(null, y / args.dpm);
}
}
move(null, null, .5)
x+=args.dpm;
move(x / args.dpm);
for (var y = h; y>=0; y--) {
var v = Math.max(waterline, f32a[y*h + x] * args.depth);
if (typeof args.smooth !== 'undefined') {
move(null, y / args.dpm, v);
} else {
move(null, null, v);
move(null, y / args.dpm);
}
}
move(null, null, .5);
}
move(null, null, 5);
}
}
if (args.url.indexOf('://') < 0) {
args.url = 'file://' + args.url;
}
img.src = args.url;
{
"dependencies": {
"htmlimage": "^1.1.0",
"ndarray": "^1.0.15",
"yargs": "^1.2.6"
}
}
node bitmap2gcode.js --smooth --url=file:///Users/tmpvar/work/js/bitmap2gcode/ssgithub.png --depth=-5 --depthPerPass=1 --dpm=10 --rmult=2 --gmult=.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment