compressImg.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. var isFn = require('./isFn');
  2. var loadImg = require('./loadImg');
  3. var noop = require('./noop');
  4. var defaults = require('./defaults');
  5. var createUrl = require('./createUrl');
  6. var isStr = require('./isStr');
  7. exports = function(file, options, cb) {
  8. if (isFn(options)) {
  9. cb = options;
  10. options = {};
  11. }
  12. cb = cb || noop;
  13. options = options || {};
  14. defaults(options, defOptions);
  15. options.mimeType = options.mimeType || file.type;
  16. if (isStr(file)) {
  17. options.isUrl = true;
  18. } else {
  19. file = createUrl(file);
  20. }
  21. loadImg(file, function(err, img) {
  22. if (err) return cb(err);
  23. compress(img, options, cb);
  24. });
  25. };
  26. function compress(img, options, cb) {
  27. var canvas = document.createElement('canvas');
  28. var ctx = canvas.getContext('2d');
  29. var width = img.width;
  30. var height = img.height;
  31. var ratio = width / height;
  32. var maxWidth = options.maxWidth;
  33. var maxHeight = options.maxHeight;
  34. if (options.width || options.height) {
  35. if (options.width) {
  36. width = options.width;
  37. height = width / ratio;
  38. } else if (options.height) {
  39. height = options.height;
  40. width = height * ratio;
  41. }
  42. } else {
  43. if (width > maxWidth) {
  44. width = maxWidth;
  45. height = width / ratio;
  46. }
  47. if (height > maxHeight) {
  48. height = maxHeight;
  49. width = height * ratio;
  50. }
  51. }
  52. width = floor(width);
  53. height = floor(height);
  54. canvas.width = width;
  55. canvas.height = height;
  56. ctx.drawImage(img, 0, 0, width, height);
  57. if (URL && options.isUrl) URL.revokeObjectURL(img.src);
  58. if (canvas.toBlob) {
  59. try {
  60. canvas.toBlob(
  61. function(file) {
  62. cb(null, file);
  63. },
  64. options.mimeType,
  65. options.quality
  66. );
  67. } catch (e) {
  68. cb(e);
  69. }
  70. } else {
  71. cb(new Error('Canvas toBlob is not supported'));
  72. }
  73. }
  74. var defOptions = {
  75. maxWidth: Infinity,
  76. maxHeight: Infinity,
  77. quality: 0.8
  78. };
  79. var floor = Math.floor;
  80. module.exports = exports;