Sharp: Sharp takes a long time to resize a PNG image

Created on 2 Dec 2019  路  2Comments  路  Source: lovell/sharp

I am trying to resize a PNG image using sharp but it takes a long time (around 8 seconds on lambda, 6 seconds on my local machine.

Could you let me know what I need to do to improve the performance?

The code used

`import sharp, { WriteableMetadata } from "sharp";

import { writeFileSync } from "fs";

const myfunc = async () => {
const x = await sharp("./myImage.png")
.sequentialRead(true)
.resize(1024)
.withMetadata({} as WriteableMetadata) // Required for some devices.
.toBuffer();

writeFileSync("./output.png", x);

}

myfunc();`

I have attached the image I am trying to resize

Your help is highly appreciated.

myImage

question

Most helpful comment

Running this code locally takes about 3.5 seconds:

real    0m3.301s
user    0m3.422s
sys 0m0.036s

Callgrind suggests ~84% of this is spent within zlib's longest_match function.

7,964,039,511  ???:longest_match
  451,219,968  libvips/resample/templates.h:vips_reducev_gen(_VipsRegion*, void*, void*, void*, int*)
  243,597,816  libvips/resample/templates.h:vips_reduceh_gen(_VipsRegion*, void*, void*, void*, int*)
   91,456,177  libvips/conversion/premultiply.c:vips_premultiply_gen
   81,966,801  ???:inflate_fast
   75,690,354  ???:deflate_slow
   71,327,742  /build/glibc-KRRWSm/glibc-2.29/string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms

You can alter the compressionLevel property of sharp's png() function to control how much effort zlib should spend:

https://sharp.pixelplumbing.com/en/stable/api-output/#png

For example using png({ compressionLevel: 6 }) reduces the time to less than half a second:

real    0m0.347s
user    0m0.462s
sys 0m0.041s

All 2 comments

Running this code locally takes about 3.5 seconds:

real    0m3.301s
user    0m3.422s
sys 0m0.036s

Callgrind suggests ~84% of this is spent within zlib's longest_match function.

7,964,039,511  ???:longest_match
  451,219,968  libvips/resample/templates.h:vips_reducev_gen(_VipsRegion*, void*, void*, void*, int*)
  243,597,816  libvips/resample/templates.h:vips_reduceh_gen(_VipsRegion*, void*, void*, void*, int*)
   91,456,177  libvips/conversion/premultiply.c:vips_premultiply_gen
   81,966,801  ???:inflate_fast
   75,690,354  ???:deflate_slow
   71,327,742  /build/glibc-KRRWSm/glibc-2.29/string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms

You can alter the compressionLevel property of sharp's png() function to control how much effort zlib should spend:

https://sharp.pixelplumbing.com/en/stable/api-output/#png

For example using png({ compressionLevel: 6 }) reduces the time to less than half a second:

real    0m0.347s
user    0m0.462s
sys 0m0.041s

Thanks for your reply, You can close the issue.

Was this page helpful?
0 / 5 - 0 ratings