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
29.13k stars 1.3k forks source link

Enhancement: allow ensureAlpha to set the alpha transparency level #2634

Closed mtaylor-tbpm closed 3 years ago

mtaylor-tbpm commented 3 years ago

I'm re-writing an older .NET program that uses ImageMagick and need help mapping image operations. I'm also not very familiar with image processing so bear with me :) Using Node.js and the npm Sharp package.

The program has multiple conversion paths/outputs per input image and Sharp is working great except for one path where the ImageMagick output looks different from the Sharp output. The IM image is fully transparent and the Sharp image has visible areas. I suspect it's related to alpha and transparency.

Below is a sample of the old code. I'm not sure about the FilterType (kernel?) and the transparent option. I also attached examples of an input image and outputs from IM and Sharp. Any help you can provide would be great. Thank you!

MagickImage image = new MagickImage('input.png'); image.FilterType = FilterType.Point; image.Scale(2500, 2500); image.Alpha(AlphaOption.Transparent); image.ColorType = ColorType.TrueColorAlpha; image.Format = MagickFormat.Png64; …process/save image

I've gotten this far...

sharp(“test.png”) .resize({ height: 2500, width: 2500, kernel: ?, }) .toColorspace('rgb16') .toFile(“output.png”)

Input

input

ImageMagick output

ImageMagick

Sharp output

Sharp

lovell commented 3 years ago

Hello, the Point filter in ImageMagick uses nearest-neighbour interpolation so try the 'nearest' kernel in sharp for its equivalent.

The AlphaOption.Transparent operation in ImageMagick creates and/or sets a fully-transparent alpha channel. The closest feature in sharp is ensureAlpha, equivalent to AlphaOption.Opaque.

This doesn't quite do what you need, but it would be a nice addition to sharp for ensureAlpha to optionally set a transparency level between 0 (default, fully-opaque) and 1 (fully-transparent).

Here's how the API to do this might look:

// PROPOSED API, NOT YET AVAILABLE

sharp(input).ensureAlpha(1)... // fully-transparent
lovell commented 3 years ago

v0.28.1 allows the alpha transparency level to be set via ensureAlpha.

https://sharp.pixelplumbing.com/api-channel#ensurealpha

mattpr commented 1 year ago

The docs say:

This is a no-op if the image already has an alpha channel.

So ensureAlpha will only set alpha if there isn't already an alpha channel present? Is there another way to change the existing alpha/transparency? Use case is when building layers for compositing and needing to adjust transparency of the entire image.

lovell commented 1 year ago

@mattpr You can chain .removeAlpha().ensureAlpha(requiredAlpha) in that order.