Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

trim() not working expect #4322

Open
5 tasks done
natuan62 opened this issue Feb 3, 2025 · 4 comments
Open
5 tasks done

trim() not working expect #4322

natuan62 opened this issue Feb 3, 2025 · 4 comments
Labels

Comments

@natuan62
Copy link

natuan62 commented Feb 3, 2025

Possible bug

Is this a possible bug in a feature of sharp, unrelated to installation?

  • Running npm install sharp completes without error.
  • Running node -e "require('sharp')" completes without error.

If you cannot confirm both of these, please open an installation issue instead.

Are you using the latest version of sharp?

  • I am using the latest version of sharp as reported by npm view sharp dist-tags.latest.

If you cannot confirm this, please upgrade to the latest version and try again before opening an issue.

If you are using another package which depends on a version of sharp that is not the latest, please open an issue against that package instead.

What is the output of running npx envinfo --binaries --system --npmPackages=sharp --npmGlobalPackages=sharp?

  System:
    OS: macOS 15.2
    CPU: (8) arm64 Apple M1
    Memory: 100.31 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.18.0 - ~/.nvm/versions/node/v20.18.0/bin/node
    Yarn: 1.22.19 - ~/.yarn/bin/yarn
    npm: 7.20.0 - ~/.config/yarn/global/node_modules/.bin/npm
    pnpm: 9.15.0 - ~/Library/pnpm/pnpm
  npmPackages:
    sharp: ^0.33.5 => 0.33.5 

Does this problem relate to file caching?

The default behaviour of libvips is to cache input files, which can lead to EBUSY or EPERM errors on Windows.
Use sharp.cache(false) to switch this feature off.

  • Adding sharp.cache(false) does not fix this problem.

Does this problem relate to images appearing to have been rotated by 90 degrees?

Images that contain EXIF Orientation metadata are not auto-oriented. By default, EXIF metadata is removed.

  • To auto-orient pixel values use the parameter-less rotate() operation.

  • To retain EXIF Orientation use keepExif().

  • Using rotate() or keepExif() does not fix this problem.

What are the steps to reproduce?

  • try add trim() option for an png image
  • after trimmed, image cut off gray color border

What is the expected behaviour?

  • after trim(), image not cut off (gray color border)

Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this problem

// index.js

const fs = require('fs');
const sharp = require('sharp');

const main = async () => {
  const file = fs.readFileSync('./input.png');
  let image = sharp(file, { limitInputPixels: false, failOn: 'none', unlimited: true });
  image.withMetadata();
  image.trim();

  const { data, info: metadata } = await image.toBuffer({ resolveWithObject: true });

  fs.writeFileSync('./output.png', data);
};

main();


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

input.png

https://github.com/user-attachments/assets/6fa90366-9550-4e28-9ab4-52b3e20d9ce1

@natuan62 natuan62 added the triage label Feb 3, 2025
@natuan62 natuan62 closed this as completed Feb 3, 2025
@natuan62 natuan62 reopened this Feb 3, 2025
@natuan62
Copy link
Author

natuan62 commented Feb 3, 2025

fixed by add background

image.trim({
    background: 'transparent',
  });

@natuan62 natuan62 closed this as completed Feb 3, 2025
@lovell lovell added question and removed triage labels Feb 3, 2025
@natuan62
Copy link
Author

Hi @lovell
I try some config options, but seem each option will work for another image. Thank you so much ! @lovell

Example

const fs = require('fs');
const sharp = require('sharp');

const arr = ['2.png', '3.png'];

const trimPngHandler = async () => {
  const sharpParams = {
    limitInputPixels: false,
    failOn: 'none',
    failOnError: false,
  };

  await Promise.all(
    arr.map(async (item) => {
      const fileBuffer = fs.readFileSync(`./assets-input/${item}`);
      const originalImage = sharp(fileBuffer, sharpParams);
      const trimmedPng = originalImage.trim(); // 3.png is cut-off error
      // const trimmedPng = originalImage.trim({ background: '#00000000' }); // 2.png is cut-off error
      // const trimmedPng = originalImage.trim({ background: 'transparent' }); // 2.png is cut-off error
      // const trimmedPng = originalImage.trim({ background: { r: 255, g: 255, b: 255, alpha: 0 } }); // 3.png is cut-off error
      // const trimmedPng = originalImage.trim({ background: { r: 0, g: 0, b: 0, alpha: 0 } }); // 2.png is cut-off error

      const { data, info: metadata } = await trimmedPng.toBuffer({ resolveWithObject: true });
      fs.writeFileSync(`./assets-output/trimmed-${item}`, data);
    })
  );
};

trimPngHandler();

trim-image-test.zip

@natuan62 natuan62 reopened this Mar 29, 2025
@natuan62
Copy link
Author

I fixed by check hasAlpha before trim()

const metadata = await originalImage.metadata();
if (metadata.hasAlpha) {
  // 
}

@lovell
Copy link
Owner

lovell commented Apr 3, 2025

Did you see https://sharp.pixelplumbing.com/api-resize#trim ?

Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants