Visitar URL original
[Feature] add margin/pad parameter to trim() · Issue #4480 · lovell/sharp · GitHub
Skip to content

[Feature] add margin/pad parameter to trim() #4480

Closed

Description

@eddienubes

Feature request

What are you trying to achieve?

I have a bulk of small images which I .trim() to zoom into the actual content.
Later on, I run some analysis on the image which performs better with padding/margin.
Instead of trimming all the way to the content, I'd like to keep a small padding/margin around it.

When you searched for similar feature requests, what did you find that might be related?

#128

What would you expect the API to look like?

await sharp(input)
  .trim({
    threshold: 0,
    marginPx: 10 // 10px margin around the image when trimming
  })
  .toFile(output);

What alternatives have you considered?

I'm aware of the .extend() that may help achieve the same thing but it defaults to black as a background colour. I'd like to preserve the original shade.
I suppose, I could also pull the top-left pixel colour, trim and then apply extend with the same colour. However, that may lose potential gradient backgrounds that still fall into the trimming threshold.

In addition, I'm willing to contribute the feature.

Please provide sample image(s) that help explain this feature

Before

Image

After with margin/padding

Image

Activity

  1. lovell commented on Dec 10, 2025

    @lovell
    Owner

    Sounds good, happy to review and help with a PR that implements this if you're able, thank you. In terms of naming I think margin would be a good name for the property that provides this feature.

  2. added this to the v0.35.0 milestone on Jan 2, 2026
  3. lovell commented on Jun 10, 2026

    @lovell
    Owner

    sharp v0.35.0 now available, thanks again for the PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions