thumb.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * Extend proto.
  3. */
  4. module.exports = function (proto) {
  5. proto.thumb = function thumb (w, h, name, quality, align, callback) {
  6. var self = this
  7. , args = Array.prototype.slice.call(arguments);
  8. callback = args.pop();
  9. w = args.shift();
  10. h = args.shift();
  11. name = args.shift();
  12. quality = args.shift() || 63;
  13. align = args.shift() || 'topleft';
  14. self.size(function (err, size) {
  15. if (err) {
  16. return callback.apply(self, arguments);
  17. }
  18. w = parseInt(w, 10);
  19. h = parseInt(h, 10);
  20. var w1, h1;
  21. var xoffset = 0;
  22. var yoffset = 0;
  23. if (size.width < size.height) {
  24. w1 = w;
  25. h1 = Math.floor(size.height * (w/size.width));
  26. if (h1 < h) {
  27. w1 = Math.floor(w1 * (((h-h1)/h) + 1));
  28. h1 = h;
  29. }
  30. } else if (size.width > size.height) {
  31. h1 = h;
  32. w1 = Math.floor(size.width * (h/size.height));
  33. if (w1 < w) {
  34. h1 = Math.floor(h1 * (((w-w1)/w) + 1));
  35. w1 = w;
  36. }
  37. } else if (size.width == size.height) {
  38. var bigger = (w>h?w:h);
  39. w1 = bigger;
  40. h1 = bigger;
  41. }
  42. if (align == 'center') {
  43. if (w < w1) {
  44. xoffset = (w1-w)/2;
  45. }
  46. if (h < h1) {
  47. yoffset = (h1-h)/2;
  48. }
  49. }
  50. self
  51. .quality(quality)
  52. .in("-size", w1+"x"+h1)
  53. .scale(w1, h1)
  54. .crop(w, h, xoffset, yoffset)
  55. .noProfile()
  56. .write(name, function () {
  57. callback.apply(self, arguments)
  58. });
  59. });
  60. return self;
  61. }
  62. }