Skip to content

Instantly share code, notes, and snippets.

@tlhunter
Created November 2, 2015 00:06
Show Gist options
  • Save tlhunter/c21f19fb2bb78eebe615 to your computer and use it in GitHub Desktop.
Save tlhunter/c21f19fb2bb78eebe615 to your computer and use it in GitHub Desktop.
Flips every item in a PNG spritesheet horizontally, maintaining position
#!/usr/bin/env node
/**
* Flips each item in a spritesheet horizontally, maintaining position
* @author Thomas Hunter II <me@thomashunter.name>
*
* 1) Execute `npm install lwip async`
* 2) Delete the following conditional in the lwip node_module:
* https://github.com/EyalAr/lwip/blob/1138482318e79ee6c69706b544ed5d6ffe11391c/lib/ImagePrototypeInit.js#L467
*/
var lwip = require('lwip');
var async = require('async');
// TODO: These should be CLI arguments as well
var W = 16;
var H = 16;
var FLIP = 'x'; // x, y, xy
var filename = process.argv[2];
var output = process.argv[3];
var ops = [];
if (!filename || !output) {
console.log('USAGE: flip.js old.png new.png');
process.exit(-1);
}
lwip.open(filename, function(err, source) {
if (err) throw err;
var WIDTH = source.width();
var HEIGHT = source.height();
var PER_ROW = WIDTH / W;
var ROWS = HEIGHT / H;
console.log('width', WIDTH, 'height', HEIGHT);
console.log('per row', PER_ROW, 'rows', ROWS);
for (var y = 0; y < ROWS; y++) {
for (var x = 0; x < PER_ROW; x++) {
ops.push({
t: y * H,
r: (x + 1) * W,
b: (y + 1) * H,
l: x * W
});
}
}
var final_destination;
lwip.create(WIDTH, HEIGHT, function(err, first_dest) {
if (err) { return done(err); }
final_destination = first_dest;
async.mapSeries(ops, function(data, done) {
console.log('PROCESSING...', data);
source.extract(data.l, data.t, data.r, data.b, function(err, cropped) {
if (err) { return done(err); }
cropped.flip(FLIP, function(err, flipped) {
if (err) { return done(err); }
console.log('paste', data.l, data.t);
console.log('dimen', final_destination.width());
final_destination.paste(data.l, data.t, flipped, function(err, destination) {
if (err) { return done(err); }
final_destination = destination;
done(null);
});
});
});
}, function(err) {
if (err) { throw err; }
final_destination.writeFile(output, function(err) {
if (err) { throw err; }
console.log('fin.');
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment