lovell / sharp

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.
https://sharp.pixelplumbing.com
Apache License 2.0
28.91k stars 1.29k forks source link

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

Open SuperDTF opened 3 weeks ago

SuperDTF commented 3 weeks ago

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;
    }
};
lovell commented 3 weeks ago

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

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