sharp icon indicating copy to clipboard operation
sharp copied to clipboard

How do make solid border around image instead of a blur?

Open SuperDTF opened this issue 1 year ago • 1 comments

1

This code keeps giving me a blur instead of a composite layer with a solid outline. Anyway to achieve this using sharp?

const drawOutlineSharp = async (
    input,
    thickness = 10,
    backgroundColor = { r: 255, g: 255, b: 255, alpha: 1 }
) => {
    try {
        let sharpInstance = sharp(input);
        const metadata = await sharpInstance.metadata();
        console.log('Image metadata:', metadata);

        // Step 1: Create a blurred outline
        const blurredOutline = await sharpInstance
            .clone()
            .blur(thickness)
            .toBuffer();

        // Step 2: Tint the blurred outline
        const tintedOutline = await sharp(blurredOutline)
            .tint(backgroundColor)
            .toBuffer();

        // Step 3: Composite the original image over the tinted outline
        const result = await sharp(tintedOutline)
            .composite([
                {
                    input: await sharpInstance.toBuffer(),
                    blend: 'over'
                }
            ])
            .png()
            .toBuffer();

        console.log('Final image composited. Buffer size:', result.length);

        return sharp(result);
    } catch (error) {
        console.error('Error in drawOutlineSharp:', error);
        throw error;
    }
};

SuperDTF avatar Aug 22 '24 21:08 SuperDTF

You should be able to composite the original input directly and avoid an unnecessary decode/encode round-trip.

-                    input: await sharpInstance.toBuffer(),
+                    input,

lovell avatar Aug 24 '24 17:08 lovell

I hope this information helped. Please feel free to re-open with more details if further assistance is required.

lovell avatar Sep 23 '24 19:09 lovell