index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { isNodePattern, throwError } from '@jimp/utils';
  2. /**
  3. * Applies a minimum color threshold to a greyscale image. Converts image to greyscale by default
  4. * @param {number} options object
  5. * max: A number auto limited between 0 - 255
  6. * replace: (optional) A number auto limited between 0 - 255 (default 255)
  7. * autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true)
  8. * @param {number} cb (optional) a callback for when complete
  9. * @return {this} this for chaining of methods
  10. */
  11. export default () => ({
  12. threshold({ max, replace = 255, autoGreyscale = true }, cb) {
  13. if (typeof max !== 'number') {
  14. return throwError.call(this, 'max must be a number', cb);
  15. }
  16. if (typeof replace !== 'number') {
  17. return throwError.call(this, 'replace must be a number', cb);
  18. }
  19. if (typeof autoGreyscale !== 'boolean') {
  20. return throwError.call(this, 'autoGreyscale must be a boolean', cb);
  21. }
  22. max = this.constructor.limit255(max);
  23. replace = this.constructor.limit255(replace);
  24. if (autoGreyscale) {
  25. this.greyscale();
  26. }
  27. this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {
  28. const grey =
  29. this.bitmap.data[idx] < max ? this.bitmap.data[idx] : replace;
  30. this.bitmap.data[idx] = grey;
  31. this.bitmap.data[idx + 1] = grey;
  32. this.bitmap.data[idx + 2] = grey;
  33. });
  34. if (isNodePattern(cb)) {
  35. cb.call(this, null, this);
  36. }
  37. return this;
  38. }
  39. });