JanMic
JanMic

Reputation: 11

I can't convert to jpg using node sharp

I use sharp node (https://www.npmjs.com/package/sharp) in a lambda node function to convert, crop, and white background images

I tolerate various input formats, but the image output format should always be jpg.

The problem is that in some cases sharp does not convert the image to jpg, when it happens is always with png images, it does not always happen, another problem is that sharp does not throw exceptions, ie the error is "silent".

Unfortunately I do not have the original image because I do not save this information, below is the code:

For crop:

image.extract(offset)
    .resize(width, height)
    .toFormat('jpeg')
    .jpeg({
      quality: 100,
      chromaSubsampling: '4:4:4'
    })
    .toBuffer();

To put white background:

image.flatten(true)
    .resize(width, height)
    .background(backgroundColor.white)
    .embed()
    .toFormat('jpeg')
    .jpeg({
      quality: 100,
      chromaSubsampling: '4:4:4'
    })
    .toBuffer();

Other cases:

image.flatten(true)
    .resize(width, height)
    .background(backgroundColor.white)
    .toFormat('jpeg')
    .jpeg({
      quality: 100,
      chromaSubsampling: '4:4:4'
    })
    .toBuffer();

I searched for answers to this and still can't find, has anyone been through this?

Upvotes: 0

Views: 12645

Answers (2)

Front-End-然
Front-End-然

Reputation: 42

Docs say force is true by default, but set this property is useful.

Upvotes: -2

Fdebijl
Fdebijl

Reputation: 1021

You should set force: true on the jpeg() options. If you don't, sharp will respect the input format and effectively do nothing with the jpeg() call.

Example:

image.extract(offset)
    .resize(width, height)
    .toFormat('jpeg')
    .jpeg({
      quality: 100,
      chromaSubsampling: '4:4:4',
      force: true, // <----- add this parameter
    })
    .toBuffer();

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

Upvotes: 7

Related Questions