minify.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const gm = require('gm').subClass({ imageMagick: true });
  2. const fs = require('fs');
  3. const runExtnames = ["png", "jpg", "jpeg", "gif", "bmp"]
  4. // 检查格式是否符合
  5. const extnameCheck = name => ~runExtnames.indexOf(name.toLocaleLowerCase())
  6. /**
  7. * 对图片进行缩放
  8. * @param {*} width Number 缩放宽度
  9. * height Number 缩放高度
  10. */
  11. function zoom({ width, height }) {
  12. let seft = this
  13. width = Number(width) || 0;
  14. width = width < 0 ? 0 : width;
  15. height = Number(height) || 0;
  16. height = height < 0 ? 0 : height;
  17. if (!width && !height) throw 'Invalid zoom size'
  18. if (width && height) {
  19. let { origin_width: oWdith, origin_height: oHeight } = seft
  20. let porp = width / height, oPorp = oWdith / oHeight, left, top, cWidth, cHeight;
  21. if (oPorp <= porp) {
  22. seft.resize(width);
  23. cWidth = width;
  24. cHeight = cWidth / oPorp;
  25. } else if (oPorp > porp) {
  26. seft.resize(undefined, height);
  27. cHeight = height;
  28. cWidth = cHeight * oPorp;
  29. }
  30. left = (cWidth - width) / 2;
  31. top = (cHeight - height) / 2;
  32. seft = seft.crop(width, height, left, top);
  33. } else {
  34. seft = seft.resize(width || undefined, height || undefined);
  35. }
  36. return seft;
  37. }
  38. /**
  39. * 初始化缩略图对象
  40. * @param {*} fileUri string 要进行缩放的图片本地路径
  41. * stream readStream 要进行缩放的图片的可读流
  42. * fileFormat string 要缩放的图片的后缀名
  43. * @return Promise
  44. */
  45. const init = ({ fileUri, stream }) => {
  46. if (fileUri) {
  47. stream = fs.createReadStream(fileUri);
  48. } else if (!stream) {
  49. throw 'Unknown file';
  50. }
  51. return new Promise((resolve, reject) => {
  52. gm(stream).size({ bufferStream: true }, function (err, val) {
  53. if (err) {
  54. reject(err)
  55. } else {
  56. let result = Object.create(this);
  57. result.origin_width = val.width;
  58. result.origin_height = val.height;
  59. result.zoom = zoom;
  60. resolve(result);
  61. }
  62. });
  63. });
  64. }
  65. module.exports = exports = {
  66. runExtnames,
  67. init,
  68. extnameCheck
  69. };