Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import config from '../config'
- import sharp from 'sharp'
- import S3 from 'aws-sdk/clients/s3'
- class ImageCop {
- constructor(key) {
- this.key = key
- this.config = config
- this.sharp
- this.s3 = this.initializeS3()
- }
- /**
- * Initialize the s3 client.
- */
- initializeS3() {
- return new S3({
- params: { Bucket: this.config.bucket },
- apiVersion: '2006-03-01',
- region: this.config.region,
- credentials: {
- accessKeyId: this.config.credentials.key,
- secretAccessKey: this.config.credentials.secret
- }
- })
- }
- compress() {
- this.s3.getObject(
- {
- Bucket: 'image-cop',
- Key: decodeURI(this.key)
- },
- (err, data) => {
- // Handle any error and exit
- if (err) {
- console.log('Image Cop', err)
- return err
- }
- const image = sharp(data.Body)
- image
- .metadata()
- .then(metadata => {
- /**
- * Sharp uses different methods with
- * different parameters depending
- * on mimetype.
- */
- // JPEG
- if (metadata.format == 'jpeg') {
- image.jpeg(this.config.imageSettings.jpeg)
- }
- if (metadata.format == 'png') {
- image.png(this.config.imageSettings.png)
- }
- // fix issue where image was rotating.
- image.rotate()
- // enforce max width of any image in library.
- if (metadata.width > this.config.maxWidth) {
- image.resize(this.config.maxWidth)
- }
- return image.toBuffer()
- })
- .then(data => {
- /**
- * Move the compressed image to the output folder.
- */
- this.s3
- .putObject({
- Bucket: this.config.bucket,
- Key:
- this.config.outputFolder +
- this.key.replace(this.config.targetFolder, ''),
- Body: new Buffer(data, 'binary'),
- ACL: 'public-read'
- })
- .promise()
- .then(function(data) {
- console.log(data)
- })
- .catch(function(err) {
- console.log('Image Cop', err)
- })
- })
- .catch(err => {
- console.log('Image Cop', err)
- })
- }
- )
- }
- }
- export default ImageCop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement