Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. import config from '../config'
  2. import sharp from 'sharp'
  3. import S3 from 'aws-sdk/clients/s3'
  4.  
  5. class ImageCop {
  6. constructor(key) {
  7. this.key = key
  8. this.config = config
  9. this.sharp
  10. this.s3 = this.initializeS3()
  11. }
  12.  
  13. /**
  14. * Initialize the s3 client.
  15. */
  16. initializeS3() {
  17. return new S3({
  18. params: { Bucket: this.config.bucket },
  19. apiVersion: '2006-03-01',
  20. region: this.config.region,
  21. credentials: {
  22. accessKeyId: this.config.credentials.key,
  23. secretAccessKey: this.config.credentials.secret
  24. }
  25. })
  26. }
  27.  
  28. compress() {
  29. this.s3.getObject(
  30. {
  31. Bucket: 'image-cop',
  32. Key: decodeURI(this.key)
  33. },
  34. (err, data) => {
  35. // Handle any error and exit
  36. if (err) {
  37. console.log('Image Cop', err)
  38. return err
  39. }
  40.  
  41. const image = sharp(data.Body)
  42.  
  43. image
  44. .metadata()
  45.  
  46. .then(metadata => {
  47. /**
  48. * Sharp uses different methods with
  49. * different parameters depending
  50. * on mimetype.
  51. */
  52.  
  53. // JPEG
  54. if (metadata.format == 'jpeg') {
  55. image.jpeg(this.config.imageSettings.jpeg)
  56. }
  57.  
  58. if (metadata.format == 'png') {
  59. image.png(this.config.imageSettings.png)
  60. }
  61. // fix issue where image was rotating.
  62. image.rotate()
  63.  
  64. // enforce max width of any image in library.
  65. if (metadata.width > this.config.maxWidth) {
  66. image.resize(this.config.maxWidth)
  67. }
  68. return image.toBuffer()
  69. })
  70.  
  71. .then(data => {
  72. /**
  73. * Move the compressed image to the output folder.
  74. */
  75. this.s3
  76. .putObject({
  77. Bucket: this.config.bucket,
  78. Key:
  79. this.config.outputFolder +
  80. this.key.replace(this.config.targetFolder, ''),
  81. Body: new Buffer(data, 'binary'),
  82. ACL: 'public-read'
  83. })
  84. .promise()
  85. .then(function(data) {
  86. console.log(data)
  87. })
  88. .catch(function(err) {
  89. console.log('Image Cop', err)
  90. })
  91. })
  92.  
  93. .catch(err => {
  94. console.log('Image Cop', err)
  95. })
  96. }
  97. )
  98. }
  99. }
  100.  
  101. export default ImageCop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement