morph.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * Module dependencies.
  3. */
  4. var fs = require('fs');
  5. var parallel = require('array-parallel');
  6. /**
  7. * Extend proto.
  8. */
  9. module.exports = function (proto) {
  10. /**
  11. * Do nothing.
  12. */
  13. function noop () {}
  14. // http://www.graphicsmagick.org/GraphicsMagick.html#details-morph
  15. proto.morph = function morph (other, outname, callback) {
  16. if (!outname) {
  17. throw new Error("an output filename is required");
  18. }
  19. callback = (callback || noop).bind(this)
  20. var self = this;
  21. if (Array.isArray(other)) {
  22. other.forEach(function (img) {
  23. self.out(img);
  24. });
  25. self.out("-morph", other.length);
  26. } else {
  27. self.out(other, "-morph", 1);
  28. }
  29. self.write(outname, function (err, stdout, stderr, cmd) {
  30. if (err) return callback(err, stdout, stderr, cmd);
  31. // Apparently some platforms create the following temporary files.
  32. // Check if the output file exists, if it doesn't, then
  33. // work with temporary files.
  34. fs.exists(outname, function (exists) {
  35. if (exists) return callback(null, stdout, stderr, cmd);
  36. parallel([
  37. fs.unlink.bind(fs, outname + '.0'),
  38. fs.unlink.bind(fs, outname + '.2'),
  39. fs.rename.bind(fs, outname + '.1', outname)
  40. ], function (err) {
  41. callback(err, stdout, stderr, cmd);
  42. })
  43. })
  44. });
  45. return self;
  46. }
  47. }