4

I have an aws image file and Iam compressing the image using sharp , but after compressing, the file size is increasing hugely . In my case I have an image size of 6.5MB , which after compressing it is becoming 19.5MB.

The following is my code :

const width = parseInt(image.height);
const height = parseInt(image.width);

var getObjectParams = {
  Bucket: BUCKET,
  Key: FILE_NAME
}

  s3.getObject(getObjectParams).promise()
    .then(data => {
      sharp(data.Body)
       .resize(width, height)
        .ignoreAspectRatio()
        .toFormat('png')
        .toBuffer()
        .then((buffer) => {
         ........
         ........
    }

I have even tried using .max() ,

 sharp(data.Body)
 .withoutEnlargement()
 .resize(width, height)
 .toFormat('png')
 .toBuffer()

The same issue , file size is increasing . In my case the image aspect ratio should be maintained. Any suggestions would be appreciated. Thanks

Shaik Nizamuddin
  • 589
  • 1
  • 7
  • 23

1 Answers1

0

This is a common problem with Sharp but yet this is a nice & amazing package. Read the Sharp documentation for png.

If you need to play around with; options.quality, options.colours, options.dither to compress a significant amount of any PNG image and according to its doc,

requires libvips compiled with support for libimagequant

So you need the help of libimagequant to achieve your goal. According to the site, libimagequant is a Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.

Instead you can use this NPM PACKAGE called imagemin and I am sure it uses the same method to compress PNG images. With a small piece of code as below, you can reduce the size of PNG.

const files = await imagemin(['images/*.{png}'], {
    destination: 'build/images',
        plugins: [
            imageminJpegtran(),
            imageminPngquant({
                quality: [0.6, 0.8]
            })
        ]
});

Play around with quality: [0.6, 0.8] like quality: [0.2, 0.2] to reduce the size and you can pass a single image file like const files = await imagemin(['fileName.png']

mapmalith
  • 1,303
  • 21
  • 38