Skip to content

How can I erase an arbitrary part of an image? #1016

@davidjoy

Description

@davidjoy

Hi there,

I'm trying to figure out how I can make part of an image transparent again (think the "eraser" tool in Photoshop). I have an image and need to be able to cut an alpha: 0 hole in an arbitrary part of it, but haven’t been able to find the right incantation!

I've been trying to do this by overlaying a transparent image the size I'm lookin' for on top of my original image using overlayWith, but I think what's going on is that because it's alpha: 0, it effectively gets composited in as a no-op and doesn't change the underlying pixels.

Here's an example of what's not quite working for me:

// Don't mind me while I await...
let overlayBuffer = await sharp({
    create: {
        width: 10,
        height: 10,
        channels: 4,
        background: {r: 0, g: 0, b: 0, alpha: 0}
    }
}).png().toBuffer(); // The "png()" seems to be necessary.

// For an example, say that "originalBuffer" here is a 100x100 image of a duck.  
// Something with real, substantive, amazing content that I want to chop a hole in.
let resultBuffer = await sharp(originalBuffer).overlayWith({
    overlayBuffer, {
        top: 8,
        left: 8,
    }
)

I want to tell overlayWith to "blow away whatever was in this particular spot and replace it with this buffer", essentially.

I've been staring at the documentation for a few hours and pouring over Github issues, and I can't find an answer; apologies if it's out there and I just couldn't find it! Thanks in advance for any advice.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions