diff --git a/docs/api-colour.md b/docs/api-colour.md index e3847c8eb..a6f7841a4 100644 --- a/docs/api-colour.md +++ b/docs/api-colour.md @@ -1,7 +1,7 @@ ## tint -> tint(rgb) ⇒ Sharp +> tint(tint) ⇒ Sharp -Tint the image using the provided chroma while preserving the image luminance. +Tint the image using the provided colour. An alpha channel may be present and will be unchanged by the operation. @@ -12,7 +12,7 @@ An alpha channel may be present and will be unchanged by the operation. | Param | Type | Description | | --- | --- | --- | -| rgb | string \| Object | parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. | +| tint | String \| Object | Parsed by the [color](https://www.npmjs.org/package/color) module. | **Example** ```js diff --git a/docs/changelog.md b/docs/changelog.md index 8626761ef..a92d38926 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -20,6 +20,10 @@ Requires libvips v8.15.0 * Options for `trim` operation must be an Object, add new `lineArt` option. [#2363](https://github.com/lovell/sharp/issues/2363) +* Improve luminance of `tint` operation with weighting function. + [#3338](https://github.com/lovell/sharp/issues/3338) + [@jcupitt](https://github.com/jcupitt) + * Ensure all `Error` objects contain a `stack` property. [#3653](https://github.com/lovell/sharp/issues/3653) diff --git a/docs/search-index.json b/docs/search-index.json index aa5833e4d..67a517394 100644 --- a/docs/search-index.json +++ b/docs/search-index.json @@ -1 +1 @@ -[{"t":"Prerequisites","d":"Node-API v9 compatible runtime e.g. Node.js 18.17.0","k":"prerequisites node api compatible runtime","l":"/install#prerequisites"},{"t":"Prebuilt binaries","d":"Ready-compiled sharp and libvips binaries are provided for use on the most common platforms macOS x64 10.13 macOS ARM64 Linux ARM glibc 2.28 Linux ARM64 glibc 2.26, musl 1.2.2 Linux s390x glibc 2.28 L","k":"prebuilt binaries compiled libvips common platforms macos arm linux glibc musl","l":"/install#prebuilt-binaries"},{"t":"Custom libvips","d":"To use a custom, globally-installed version of libvips instead of the provided binaries, make sure it is at least the version listed under engines.libvips in the package.json file and that it can be l","k":"custom libvips globally installed version instead binaries listed engines package json file","l":"/install#custom-libvips"},{"t":"Building from source","d":"This module will be compiled from source at npm install time when a globally-installed libvips is detected set the SHARP_IGNORE_GLOBAL_LIBVIPS environment variable to skip this, or when the npm instal","k":"building source module compiled npm install time globally installed libvips detected environment variable skip instal","l":"/install#building-from-source"},{"t":"WebAssembly","d":"Experimental support is provided for runtime environments that provide multi-threaded Wasm via Workers. sh npm install --cpuwasm32 sharp","k":"webassembly experimental runtime environments multi threaded wasm workers npm install cpuwasm","l":"/install#webassembly"},{"t":"FreeBSD","d":"The vips package must be installed before npm install is run. sh pkg install -y pkgconf vips sh cd /usr/ports/graphics/vips/ make install clean","k":"freebsd vips package installed npm install pkg pkgconf usr ports graphics clean","l":"/install#freebsd"},{"t":"Linux memory allocator","d":"The default memory allocator on most glibc-based Linux systems e.g. Debian, Red Hat is unsuitable for long-running, multi-threaded processes that involve lots of small memory allocations. For this rea","k":"linux memory allocator glibc systems debian red hat long running multi threaded processes small allocations rea","l":"/install#linux-memory-allocator"},{"t":"AWS Lambda","d":"The node_modules directory of the deployment package must include binaries for either the linux-x64 or linux-arm64 platforms depending on the chosen architecture. When building your deployment package","k":"aws lambda nodemodules directory deployment package binaries linux arm platforms depending chosen architecture building","l":"/install#aws-lambda"},{"t":"webpack","d":"Ensure sharp is excluded from bundling via the externals configuration. js externals sharp commonjs sharp","k":"webpack excluded bundling externals configuration commonjs","l":"/install#webpack"},{"t":"esbuild","d":"Ensure sharp is excluded from bundling via the external","k":"esbuild excluded bundling external","l":"/install#esbuild"},{"t":"TypeScript","d":"TypeScript definitions are published as part of the sharp package from v0.32.0. Previously these were available via the types/sharp package, which is now deprecated. When using Typescript, please ensu","k":"typescript definitions published package types deprecated ensu","l":"/install#typescript"},{"t":"Fonts","d":"When creating text images or rendering SVG images that contain text elements, fontconfig is used to find the relevant fonts. On Windows and macOS systems, all system fonts are available for use. On ma","k":"fonts creating text images rendering svg contain elements fontconfig find relevant windows macos systems system","l":"/install#fonts"},{"t":"Canvas and Windows","d":"If both canvas and sharp modules are used in the same Windows process, the following error may occur The specified procedure could not be found.","k":"canvas windows modules process error procedure could found","l":"/install#canvas-and-windows"},{"t":"Sharp","d":"Emits codeSharpeventinfo/code, codeSharpeventwarning/code a namenew_Sharp_new/a","k":"emits code fail limit input pixels unlimited sequential read density ignore icc pages page subifd level animated raw create text","l":"/api-constructor#sharp"},{"t":"clone","d":"Take a snapshot of the Sharp instance, returning a new instance. Cloned instances inherit the input of their parent instance. This allows multiple output Streams and therefore multiple processing pip","k":"clone snapshot instance returning new cloned instances inherit input parent multiple output streams processing pip","l":"/api-constructor#clone"},{"t":"metadata","d":"Fast access to uncached image metadata without decoding any compressed pixel data.","k":"metadata fast access uncached decoding compressed pixel data","l":"/api-input#metadata"},{"t":"stats","d":"Access to pixel-derived image statistics for every channel in the image. A Promise is returned when callback is not provided.","k":"stats access pixel derived statistics channel promise","l":"/api-input#stats"},{"t":"toFile","d":"Write output image data to a file.","k":"tofile write output data file","l":"/api-output#tofile"},{"t":"toBuffer","d":"Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.","k":"tobuffer write output buffer jpeg png webp avif tiff gif raw pixel data resolve object","l":"/api-output#tobuffer"},{"t":"withMetadata","d":"Include all metadata EXIF, XMP, IPTC from the input image in the output image. This will also convert to and add a web-friendly sRGB ICC profile if appropriate, unless a custom output profile is prov","k":"withmetadata metadata exif xmp iptc input output convert add web friendly srgb icc profile appropriate custom prov orientation density","l":"/api-output#withmetadata"},{"t":"toFormat","d":"Force output to a given format.","k":"toformat force output format","l":"/api-output#toformat"},{"t":"jpeg","d":"Use these JPEG options for output image.","k":"jpeg output quality progressive chroma subsampling optimise coding optimize mozjpeg trellis quantisation overshoot deringing scans table quantization force","l":"/api-output#jpeg"},{"t":"png","d":"Use these PNG options for output image.","k":"png output progressive compression level adaptive filtering palette quality effort colours colors dither force","l":"/api-output#png"},{"t":"webp","d":"Use these WebP options for output image.","k":"webp output quality alpha lossless near smart subsample preset effort loop delay min size mixed force","l":"/api-output#webp"},{"t":"gif","d":"Use these GIF options for the output image.","k":"gif output reuse progressive colours colors effort dither inter frame max error palette loop delay force","l":"/api-output#gif"},{"t":"tiff","d":"Use these TIFF options for output image.","k":"tiff output quality force compression predictor pyramid tile width height xres yres resolution unit bitdepth miniswhite","l":"/api-output#tiff"},{"t":"avif","d":"Use these AVIF options for output image.","k":"avif output quality lossless effort chroma subsampling","l":"/api-output#avif"},{"t":"heif","d":"Use these HEIF options for output image.","k":"heif output compression quality lossless effort chroma subsampling","l":"/api-output#heif"},{"t":"jxl","d":"Use these JPEG-XL JXL options for output image.","k":"jxl jpeg output distance quality decoding tier lossless effort depth","l":"/api-output#jxl"},{"t":"tile","d":"Use tile-based deep zoom image pyramid output.","k":"tile deep zoom pyramid output size overlap angle background depth skip blanks container layout centre center basename","l":"/api-output#tile"},{"t":"timeout","d":"Set a timeout for processing, in seconds. Use a value of zero to continue processing indefinitely, the default behaviour.","k":"timeout processing seconds zero continue indefinitely behaviour","l":"/api-output#timeout"},{"t":"resize","d":"Resize image to width, height or width x height.","k":"resize width height fit position background kernel enlargement reduction fast shrink load","l":"/api-resize#resize"},{"t":"extend","d":"Extend / pad / extrude one or more edges of the image with either the provided background colour or pixels derived from the image. This operation will always occur after resizing and extraction, if a","k":"extend pad extrude edges background colour pixels derived operation resizing extraction","l":"/api-resize#extend"},{"t":"extract","d":"Extract/crop a region of the image.","k":"extract crop region left top width height","l":"/api-resize#extract"},{"t":"trim","d":"Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.","k":"trim pixels edges contain similar background colour defaults top left pixel threshold line art","l":"/api-resize#trim"},{"t":"composite","d":"Composite images over the processed resized, extracted etc. image.","k":"composite images processed resized extracted","l":"/api-composite#composite"},{"t":"rotate","d":"Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag.","k":"rotate output explicit angle auto orient exif orientation tag background","l":"/api-operation#rotate"},{"t":"flip","d":"Mirror the image vertically up-down about the x-axis. This always occurs before rotation, if any.","k":"flip mirror vertically down axis rotation","l":"/api-operation#flip"},{"t":"flop","d":"Mirror the image horizontally left-right about the y-axis. This always occurs before rotation, if any.","k":"flop mirror horizontally left right axis rotation","l":"/api-operation#flop"},{"t":"affine","d":"Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.","k":"affine transform operation resizing extraction rotation background idx idy odx ody interpolator","l":"/api-operation#affine"},{"t":"sharpen","d":"Sharpen the image.","k":"sharpen sigma","l":"/api-operation#sharpen"},{"t":"median","d":"Apply median filter. When used without parameters the default window is 3x3.","k":"median apply filter parameters window","l":"/api-operation#median"},{"t":"blur","d":"Blur the image.","k":"blur","l":"/api-operation#blur"},{"t":"flatten","d":"Merge alpha transparency channel, if any, with a background, then remove the alpha channel.","k":"flatten merge alpha transparency channel background remove","l":"/api-operation#flatten"},{"t":"unflatten","d":"Ensure the image has an alpha channel with all white pixel values made fully transparent.","k":"unflatten alpha channel white pixel made fully transparent","l":"/api-operation#unflatten"},{"t":"gamma","d":"Apply a gamma correction by reducing the encoding darken pre-resize at a factor of 1/gamma then increasing the encoding brighten post-resize at a factor of gamma. This can improve the perceived brigh","k":"gamma apply correction reducing encoding darken resize factor increasing brighten post improve perceived brigh alpha","l":"/api-operation#gamma"},{"t":"normalise","d":"Enhance output image contrast by stretching its luminance to cover a full dynamic range.","k":"normalise enhance output contrast stretching luminance cover full dynamic range lower upper","l":"/api-operation#normalise"},{"t":"normalize","d":"Alternative spelling of normalise.","k":"normalize normalise lower upper","l":"/api-operation#normalize"},{"t":"clahe","d":"Perform contrast limiting adaptive histogram equalization CLAHE.","k":"clahe contrast limiting adaptive histogram equalization width height max slope","l":"/api-operation#clahe"},{"t":"convolve","d":"Convolve the image with the specified kernel.","k":"convolve kernel","l":"/api-operation#convolve"},{"t":"threshold","d":"Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.","k":"threshold pixel greater equal otherwise greyscale grayscale raw","l":"/api-operation#threshold"},{"t":"recomb","d":"Recombine the image with the specified matrix.","k":"recomb recombine matrix","l":"/api-operation#recomb"},{"t":"modulate","d":"Transforms the image using brightness, saturation, hue rotation, and lightness. Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas","k":"modulate transforms brightness saturation hue rotation lightness operate luminance difference being multiplicative whereas","l":"/api-operation#modulate"},{"t":"removeAlpha","d":"Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.","k":"removealpha remove alpha channel","l":"/api-channel#removealpha"},{"t":"ensureAlpha","d":"Ensure the output image has an alpha transparency channel. If missing, the added alpha channel will have the specified transparency level, defaulting to fully-opaque 1. This is a no-op if the image a","k":"ensurealpha output alpha transparency channel missing added level defaulting fully opaque","l":"/api-channel#ensurealpha"},{"t":"extractChannel","d":"Extract a single channel from a multi-channel image.","k":"extractchannel extract single channel multi","l":"/api-channel#extractchannel"},{"t":"joinChannel","d":"Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace. By default the output image will be web-friendly sRGB, with additi","k":"joinchannel join channels meaning added depends output colourspace tocolourspace web friendly srgb additi","l":"/api-channel#joinchannel"},{"t":"tint","d":"Tint the image using the provided chroma while preserving the image luminance. An alpha channel may be present and will be unchanged by the operation.","k":"tint chroma preserving luminance alpha channel present unchanged operation","l":"/api-colour#tint"},{"t":"greyscale","d":"Convert to 8-bit greyscale 256 shades of grey. This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use gamma with greyscale for the best results. By default t","k":"greyscale convert bit shades grey linear operation input colour space srgb gamma results","l":"/api-colour#greyscale"},{"t":"grayscale","d":"Alternative spelling of greyscale.","k":"grayscale greyscale","l":"/api-colour#grayscale"},{"t":"pipelineColorspace","d":"Alternative spelling of pipelineColourspace.","k":"","l":"/api-colour#pipelinecolorspace"},{"t":"versions","d":"An Object containing the version numbers of sharp, libvips and when using prebuilt binaries its dependencies.","k":"versions object version numbers libvips prebuilt binaries dependencies","l":"/api-utility#versions"},{"t":"interpolators","d":"An Object containing the available interpolators and their proper values","k":"interpolators object proper","l":"/api-utility#interpolators"},{"t":"queue","d":"An EventEmitter that emits a change event when a task is either - queued, waiting for _libuv_ to provide a worker thread - complete","k":"queue eventemitter emits change event queued waiting libuv worker thread complete","l":"/api-utility#queue"},{"t":"cache","d":"Gets or, when options are provided, sets the limits of _libvips_ operation cache. Existing entries in the cache will be trimmed after any change in limits. This method always returns cache statistics","k":"cache limits libvips operation existing entries trimmed change method returns statistics memory files items","l":"/api-utility#cache"},{"t":"concurrency","d":"Gets or, when a concurrency is provided, sets the maximum number of threads _libvips_ should use to process _each image_. These are from a thread pool managed by glib, which helps avoid the overhead","k":"concurrency maximum number threads libvips process thread pool managed glib helps avoid overhead","l":"/api-utility#concurrency"},{"t":"counters","d":"Provides access to internal task counters. - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool. - process is the number of resize tasks","k":"counters provides access internal queue number tasks module queued waiting libuv worker thread pool process resize","l":"/api-utility#counters"},{"t":"simd","d":"Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with liborc support.","k":"simd vector unit instructions libvips compiled liborc","l":"/api-utility#simd"},{"t":"block","d":"Block libvips operations at runtime.","k":"block libvips operations runtime operation","l":"/api-utility#block"},{"t":"unblock","d":"Unblock libvips operations at runtime.","k":"unblock libvips operations runtime operation","l":"/api-utility#unblock"}] \ No newline at end of file +[{"t":"Prerequisites","d":"Node-API v9 compatible runtime e.g. Node.js 18.17.0","k":"prerequisites node api compatible runtime","l":"/install#prerequisites"},{"t":"Prebuilt binaries","d":"Ready-compiled sharp and libvips binaries are provided for use on the most common platforms macOS x64 10.13 macOS ARM64 Linux ARM glibc 2.28 Linux ARM64 glibc 2.26, musl 1.2.2 Linux s390x glibc 2.28 L","k":"prebuilt binaries compiled libvips common platforms macos arm linux glibc musl","l":"/install#prebuilt-binaries"},{"t":"Custom libvips","d":"To use a custom, globally-installed version of libvips instead of the provided binaries, make sure it is at least the version listed under engines.libvips in the package.json file and that it can be l","k":"custom libvips globally installed version instead binaries listed engines package json file","l":"/install#custom-libvips"},{"t":"Building from source","d":"This module will be compiled from source at npm install time when a globally-installed libvips is detected set the SHARP_IGNORE_GLOBAL_LIBVIPS environment variable to skip this, or when the npm instal","k":"building source module compiled npm install time globally installed libvips detected environment variable skip instal","l":"/install#building-from-source"},{"t":"WebAssembly","d":"Experimental support is provided for runtime environments that provide multi-threaded Wasm via Workers. sh npm install --cpuwasm32 sharp","k":"webassembly experimental runtime environments multi threaded wasm workers npm install cpuwasm","l":"/install#webassembly"},{"t":"FreeBSD","d":"The vips package must be installed before npm install is run. sh pkg install -y pkgconf vips sh cd /usr/ports/graphics/vips/ make install clean","k":"freebsd vips package installed npm install pkg pkgconf usr ports graphics clean","l":"/install#freebsd"},{"t":"Linux memory allocator","d":"The default memory allocator on most glibc-based Linux systems e.g. Debian, Red Hat is unsuitable for long-running, multi-threaded processes that involve lots of small memory allocations. For this rea","k":"linux memory allocator glibc systems debian red hat long running multi threaded processes small allocations rea","l":"/install#linux-memory-allocator"},{"t":"AWS Lambda","d":"The node_modules directory of the deployment package must include binaries for either the linux-x64 or linux-arm64 platforms depending on the chosen architecture. When building your deployment package","k":"aws lambda nodemodules directory deployment package binaries linux arm platforms depending chosen architecture building","l":"/install#aws-lambda"},{"t":"webpack","d":"Ensure sharp is excluded from bundling via the externals configuration. js externals sharp commonjs sharp","k":"webpack excluded bundling externals configuration commonjs","l":"/install#webpack"},{"t":"esbuild","d":"Ensure sharp is excluded from bundling via the external","k":"esbuild excluded bundling external","l":"/install#esbuild"},{"t":"TypeScript","d":"TypeScript definitions are published as part of the sharp package from v0.32.0. Previously these were available via the types/sharp package, which is now deprecated. When using Typescript, please ensu","k":"typescript definitions published package types deprecated ensu","l":"/install#typescript"},{"t":"Fonts","d":"When creating text images or rendering SVG images that contain text elements, fontconfig is used to find the relevant fonts. On Windows and macOS systems, all system fonts are available for use. On ma","k":"fonts creating text images rendering svg contain elements fontconfig find relevant windows macos systems system","l":"/install#fonts"},{"t":"Canvas and Windows","d":"If both canvas and sharp modules are used in the same Windows process, the following error may occur The specified procedure could not be found.","k":"canvas windows modules process error procedure could found","l":"/install#canvas-and-windows"},{"t":"Sharp","d":"Emits codeSharpeventinfo/code, codeSharpeventwarning/code a namenew_Sharp_new/a","k":"emits code fail limit input pixels unlimited sequential read density ignore icc pages page subifd level animated raw create text","l":"/api-constructor#sharp"},{"t":"clone","d":"Take a snapshot of the Sharp instance, returning a new instance. Cloned instances inherit the input of their parent instance. This allows multiple output Streams and therefore multiple processing pip","k":"clone snapshot instance returning new cloned instances inherit input parent multiple output streams processing pip","l":"/api-constructor#clone"},{"t":"metadata","d":"Fast access to uncached image metadata without decoding any compressed pixel data.","k":"metadata fast access uncached decoding compressed pixel data","l":"/api-input#metadata"},{"t":"stats","d":"Access to pixel-derived image statistics for every channel in the image. A Promise is returned when callback is not provided.","k":"stats access pixel derived statistics channel promise","l":"/api-input#stats"},{"t":"toFile","d":"Write output image data to a file.","k":"tofile write output data file","l":"/api-output#tofile"},{"t":"toBuffer","d":"Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.","k":"tobuffer write output buffer jpeg png webp avif tiff gif raw pixel data resolve object","l":"/api-output#tobuffer"},{"t":"withMetadata","d":"Include all metadata EXIF, XMP, IPTC from the input image in the output image. This will also convert to and add a web-friendly sRGB ICC profile if appropriate, unless a custom output profile is prov","k":"withmetadata metadata exif xmp iptc input output convert add web friendly srgb icc profile appropriate custom prov orientation density","l":"/api-output#withmetadata"},{"t":"toFormat","d":"Force output to a given format.","k":"toformat force output format","l":"/api-output#toformat"},{"t":"jpeg","d":"Use these JPEG options for output image.","k":"jpeg output quality progressive chroma subsampling optimise coding optimize mozjpeg trellis quantisation overshoot deringing scans table quantization force","l":"/api-output#jpeg"},{"t":"png","d":"Use these PNG options for output image.","k":"png output progressive compression level adaptive filtering palette quality effort colours colors dither force","l":"/api-output#png"},{"t":"webp","d":"Use these WebP options for output image.","k":"webp output quality alpha lossless near smart subsample preset effort loop delay min size mixed force","l":"/api-output#webp"},{"t":"gif","d":"Use these GIF options for the output image.","k":"gif output reuse progressive colours colors effort dither inter frame max error palette loop delay force","l":"/api-output#gif"},{"t":"tiff","d":"Use these TIFF options for output image.","k":"tiff output quality force compression predictor pyramid tile width height xres yres resolution unit bitdepth miniswhite","l":"/api-output#tiff"},{"t":"avif","d":"Use these AVIF options for output image.","k":"avif output quality lossless effort chroma subsampling","l":"/api-output#avif"},{"t":"heif","d":"Use these HEIF options for output image.","k":"heif output compression quality lossless effort chroma subsampling","l":"/api-output#heif"},{"t":"jxl","d":"Use these JPEG-XL JXL options for output image.","k":"jxl jpeg output distance quality decoding tier lossless effort depth","l":"/api-output#jxl"},{"t":"tile","d":"Use tile-based deep zoom image pyramid output.","k":"tile deep zoom pyramid output size overlap angle background depth skip blanks container layout centre center basename","l":"/api-output#tile"},{"t":"timeout","d":"Set a timeout for processing, in seconds. Use a value of zero to continue processing indefinitely, the default behaviour.","k":"timeout processing seconds zero continue indefinitely behaviour","l":"/api-output#timeout"},{"t":"resize","d":"Resize image to width, height or width x height.","k":"resize width height fit position background kernel enlargement reduction fast shrink load","l":"/api-resize#resize"},{"t":"extend","d":"Extend / pad / extrude one or more edges of the image with either the provided background colour or pixels derived from the image. This operation will always occur after resizing and extraction, if a","k":"extend pad extrude edges background colour pixels derived operation resizing extraction","l":"/api-resize#extend"},{"t":"extract","d":"Extract/crop a region of the image.","k":"extract crop region left top width height","l":"/api-resize#extract"},{"t":"trim","d":"Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.","k":"trim pixels edges contain similar background colour defaults top left pixel threshold line art","l":"/api-resize#trim"},{"t":"composite","d":"Composite images over the processed resized, extracted etc. image.","k":"composite images processed resized extracted","l":"/api-composite#composite"},{"t":"rotate","d":"Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag.","k":"rotate output explicit angle auto orient exif orientation tag background","l":"/api-operation#rotate"},{"t":"flip","d":"Mirror the image vertically up-down about the x-axis. This always occurs before rotation, if any.","k":"flip mirror vertically down axis rotation","l":"/api-operation#flip"},{"t":"flop","d":"Mirror the image horizontally left-right about the y-axis. This always occurs before rotation, if any.","k":"flop mirror horizontally left right axis rotation","l":"/api-operation#flop"},{"t":"affine","d":"Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.","k":"affine transform operation resizing extraction rotation background idx idy odx ody interpolator","l":"/api-operation#affine"},{"t":"sharpen","d":"Sharpen the image.","k":"sharpen sigma","l":"/api-operation#sharpen"},{"t":"median","d":"Apply median filter. When used without parameters the default window is 3x3.","k":"median apply filter parameters window","l":"/api-operation#median"},{"t":"blur","d":"Blur the image.","k":"blur","l":"/api-operation#blur"},{"t":"flatten","d":"Merge alpha transparency channel, if any, with a background, then remove the alpha channel.","k":"flatten merge alpha transparency channel background remove","l":"/api-operation#flatten"},{"t":"unflatten","d":"Ensure the image has an alpha channel with all white pixel values made fully transparent.","k":"unflatten alpha channel white pixel made fully transparent","l":"/api-operation#unflatten"},{"t":"gamma","d":"Apply a gamma correction by reducing the encoding darken pre-resize at a factor of 1/gamma then increasing the encoding brighten post-resize at a factor of gamma. This can improve the perceived brigh","k":"gamma apply correction reducing encoding darken resize factor increasing brighten post improve perceived brigh alpha","l":"/api-operation#gamma"},{"t":"normalise","d":"Enhance output image contrast by stretching its luminance to cover a full dynamic range.","k":"normalise enhance output contrast stretching luminance cover full dynamic range lower upper","l":"/api-operation#normalise"},{"t":"normalize","d":"Alternative spelling of normalise.","k":"normalize normalise lower upper","l":"/api-operation#normalize"},{"t":"clahe","d":"Perform contrast limiting adaptive histogram equalization CLAHE.","k":"clahe contrast limiting adaptive histogram equalization width height max slope","l":"/api-operation#clahe"},{"t":"convolve","d":"Convolve the image with the specified kernel.","k":"convolve kernel","l":"/api-operation#convolve"},{"t":"threshold","d":"Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.","k":"threshold pixel greater equal otherwise greyscale grayscale raw","l":"/api-operation#threshold"},{"t":"recomb","d":"Recombine the image with the specified matrix.","k":"recomb recombine matrix","l":"/api-operation#recomb"},{"t":"modulate","d":"Transforms the image using brightness, saturation, hue rotation, and lightness. Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas","k":"modulate transforms brightness saturation hue rotation lightness operate luminance difference being multiplicative whereas","l":"/api-operation#modulate"},{"t":"removeAlpha","d":"Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.","k":"removealpha remove alpha channel","l":"/api-channel#removealpha"},{"t":"ensureAlpha","d":"Ensure the output image has an alpha transparency channel. If missing, the added alpha channel will have the specified transparency level, defaulting to fully-opaque 1. This is a no-op if the image a","k":"ensurealpha output alpha transparency channel missing added level defaulting fully opaque","l":"/api-channel#ensurealpha"},{"t":"extractChannel","d":"Extract a single channel from a multi-channel image.","k":"extractchannel extract single channel multi","l":"/api-channel#extractchannel"},{"t":"joinChannel","d":"Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace. By default the output image will be web-friendly sRGB, with additi","k":"joinchannel join channels meaning added depends output colourspace tocolourspace web friendly srgb additi","l":"/api-channel#joinchannel"},{"t":"tint","d":"Tint the image using the provided colour. An alpha channel may be present and will be unchanged by the operation.","k":"tint colour alpha channel present unchanged operation","l":"/api-colour#tint"},{"t":"greyscale","d":"Convert to 8-bit greyscale 256 shades of grey. This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use gamma with greyscale for the best results. By default t","k":"greyscale convert bit shades grey linear operation input colour space srgb gamma results","l":"/api-colour#greyscale"},{"t":"grayscale","d":"Alternative spelling of greyscale.","k":"grayscale greyscale","l":"/api-colour#grayscale"},{"t":"pipelineColorspace","d":"Alternative spelling of pipelineColourspace.","k":"","l":"/api-colour#pipelinecolorspace"},{"t":"versions","d":"An Object containing the version numbers of sharp, libvips and when using prebuilt binaries its dependencies.","k":"versions object version numbers libvips prebuilt binaries dependencies","l":"/api-utility#versions"},{"t":"interpolators","d":"An Object containing the available interpolators and their proper values","k":"interpolators object proper","l":"/api-utility#interpolators"},{"t":"queue","d":"An EventEmitter that emits a change event when a task is either - queued, waiting for _libuv_ to provide a worker thread - complete","k":"queue eventemitter emits change event queued waiting libuv worker thread complete","l":"/api-utility#queue"},{"t":"cache","d":"Gets or, when options are provided, sets the limits of _libvips_ operation cache. Existing entries in the cache will be trimmed after any change in limits. This method always returns cache statistics","k":"cache limits libvips operation existing entries trimmed change method returns statistics memory files items","l":"/api-utility#cache"},{"t":"concurrency","d":"Gets or, when a concurrency is provided, sets the maximum number of threads _libvips_ should use to process _each image_. These are from a thread pool managed by glib, which helps avoid the overhead","k":"concurrency maximum number threads libvips process thread pool managed glib helps avoid overhead","l":"/api-utility#concurrency"},{"t":"counters","d":"Provides access to internal task counters. - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool. - process is the number of resize tasks","k":"counters provides access internal queue number tasks module queued waiting libuv worker thread pool process resize","l":"/api-utility#counters"},{"t":"simd","d":"Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with liborc support.","k":"simd vector unit instructions libvips compiled liborc","l":"/api-utility#simd"},{"t":"block","d":"Block libvips operations at runtime.","k":"block libvips operations runtime operation","l":"/api-utility#block"},{"t":"unblock","d":"Unblock libvips operations at runtime.","k":"unblock libvips operations runtime operation","l":"/api-utility#unblock"}] \ No newline at end of file diff --git a/lib/colour.js b/lib/colour.js index a7761d29d..69309fe5a 100644 --- a/lib/colour.js +++ b/lib/colour.js @@ -19,7 +19,7 @@ const colourspace = { }; /** - * Tint the image using the provided chroma while preserving the image luminance. + * Tint the image using the provided colour. * An alpha channel may be present and will be unchanged by the operation. * * @example @@ -27,14 +27,12 @@ const colourspace = { * .tint({ r: 255, g: 240, b: 16 }) * .toBuffer(); * - * @param {string|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. + * @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module. * @returns {Sharp} * @throws {Error} Invalid parameter */ -function tint (rgb) { - const colour = color(rgb); - this.options.tintA = colour.a(); - this.options.tintB = colour.b(); +function tint (tint) { + this._setBackgroundColourOption('tint', tint); return this; } diff --git a/lib/constructor.js b/lib/constructor.js index 95fd0729a..4e624e950 100644 --- a/lib/constructor.js +++ b/lib/constructor.js @@ -212,8 +212,7 @@ const Sharp = function (input, options) { kernel: 'lanczos3', fastShrinkOnLoad: true, // operations - tintA: 128, - tintB: 128, + tint: [-1, 0, 0, 0], flatten: false, flattenBackground: [0, 0, 0], unflatten: false, diff --git a/lib/index.d.ts b/lib/index.d.ts index a781180c7..41b13ac68 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -239,12 +239,12 @@ declare namespace sharp { //#region Color functions /** - * Tint the image using the provided chroma while preserving the image luminance. + * Tint the image using the provided colour. * An alpha channel may be present and will be unchanged by the operation. - * @param rgb Parsed by the color module to extract chroma values. + * @param tint Parsed by the color module. * @returns A sharp instance that can be used to chain operations */ - tint(rgb: Color): Sharp; + tint(tint: Color): Sharp; /** * Convert to 8-bit greyscale; 256 shades of grey. diff --git a/src/operations.cc b/src/operations.cc index e14739013..e23411b41 100644 --- a/src/operations.cc +++ b/src/operations.cc @@ -16,30 +16,44 @@ using vips::VError; namespace sharp { /* - * Tint an image using the specified chroma, preserving the original image luminance + * Tint an image using the provided RGB. */ - VImage Tint(VImage image, double const a, double const b) { - // Get original colourspace + VImage Tint(VImage image, std::vector const tint) { + std::vector const tintLab = (VImage::black(1, 1) + tint) + .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)) + .getpoint(0, 0); + // LAB identity function + VImage identityLab = VImage::identity(VImage::option()->set("bands", 3)) + .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)); + // Scale luminance range, 0.0 to 1.0 + VImage l = identityLab[0] / 100; + // Weighting functions + VImage weightL = 1.0 - 4.0 * ((l - 0.5) * (l - 0.5)); + VImage weightAB = (weightL * tintLab).extract_band(1, VImage::option()->set("n", 2)); + identityLab = identityLab[0].bandjoin(weightAB); + // Convert lookup table to sRGB + VImage lut = identityLab.colourspace(VIPS_INTERPRETATION_sRGB, + VImage::option()->set("source_space", VIPS_INTERPRETATION_LAB)); + // Original colourspace VipsInterpretation typeBeforeTint = image.interpretation(); if (typeBeforeTint == VIPS_INTERPRETATION_RGB) { typeBeforeTint = VIPS_INTERPRETATION_sRGB; } - // Extract luminance - VImage luminance = image.colourspace(VIPS_INTERPRETATION_LAB)[0]; - // Create the tinted version by combining the L from the original and the chroma from the tint - std::vector chroma {a, b}; - VImage tinted = luminance - .bandjoin(chroma) - .copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_LAB)) - .colourspace(typeBeforeTint); - // Attach original alpha channel, if any + // Apply lookup table if (HasAlpha(image)) { - // Extract original alpha channel VImage alpha = image[image.bands() - 1]; - // Join alpha channel to normalised image - tinted = tinted.bandjoin(alpha); + image = RemoveAlpha(image) + .colourspace(VIPS_INTERPRETATION_B_W) + .maplut(lut) + .colourspace(typeBeforeTint) + .bandjoin(alpha); + } else { + image = image + .colourspace(VIPS_INTERPRETATION_B_W) + .maplut(lut) + .colourspace(typeBeforeTint); } - return tinted; + return image; } /* diff --git a/src/operations.h b/src/operations.h index 6e5b82d48..f2d73704a 100644 --- a/src/operations.h +++ b/src/operations.h @@ -15,9 +15,9 @@ using vips::VImage; namespace sharp { /* - * Tint an image using the specified chroma, preserving the original image luminance + * Tint an image using the provided RGB. */ - VImage Tint(VImage image, double const a, double const b); + VImage Tint(VImage image, std::vector const tint); /* * Stretch luminance to cover full dynamic range. diff --git a/src/pipeline.cc b/src/pipeline.cc index 05a2de323..9e31adeec 100644 --- a/src/pipeline.cc +++ b/src/pipeline.cc @@ -736,8 +736,8 @@ class PipelineWorker : public Napi::AsyncWorker { } // Tint the image - if (baton->tintA < 128.0 || baton->tintB < 128.0) { - image = sharp::Tint(image, baton->tintA, baton->tintB); + if (baton->tint[0] >= 0.0) { + image = sharp::Tint(image, baton->tint); } // Remove alpha channel, if any @@ -1527,8 +1527,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) { baton->normalise = sharp::AttrAsBool(options, "normalise"); baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower"); baton->normaliseUpper = sharp::AttrAsUint32(options, "normaliseUpper"); - baton->tintA = sharp::AttrAsDouble(options, "tintA"); - baton->tintB = sharp::AttrAsDouble(options, "tintB"); + baton->tint = sharp::AttrAsVectorOfDouble(options, "tint"); baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth"); baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight"); baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope"); diff --git a/src/pipeline.h b/src/pipeline.h index 86167e6e3..92ff34d41 100644 --- a/src/pipeline.h +++ b/src/pipeline.h @@ -69,8 +69,7 @@ struct PipelineBaton { bool premultiplied; bool tileCentre; bool fastShrinkOnLoad; - double tintA; - double tintB; + std::vector tint; bool flatten; std::vector flattenBackground; bool unflatten; @@ -239,8 +238,7 @@ struct PipelineBaton { attentionX(0), attentionY(0), premultiplied(false), - tintA(128.0), - tintB(128.0), + tint{ -1.0, 0.0, 0.0, 0.0 }, flatten(false), flattenBackground{ 0.0, 0.0, 0.0 }, unflatten(false), diff --git a/test/fixtures/expected/tint-alpha.png b/test/fixtures/expected/tint-alpha.png index 01620a961..1375af948 100644 Binary files a/test/fixtures/expected/tint-alpha.png and b/test/fixtures/expected/tint-alpha.png differ diff --git a/test/fixtures/expected/tint-blue.jpg b/test/fixtures/expected/tint-blue.jpg index 897864943..aad140d9b 100644 Binary files a/test/fixtures/expected/tint-blue.jpg and b/test/fixtures/expected/tint-blue.jpg differ diff --git a/test/fixtures/expected/tint-cmyk.jpg b/test/fixtures/expected/tint-cmyk.jpg index 436bc6676..5c2c67a41 100644 Binary files a/test/fixtures/expected/tint-cmyk.jpg and b/test/fixtures/expected/tint-cmyk.jpg differ diff --git a/test/fixtures/expected/tint-green.jpg b/test/fixtures/expected/tint-green.jpg index e60f90230..4facab687 100644 Binary files a/test/fixtures/expected/tint-green.jpg and b/test/fixtures/expected/tint-green.jpg differ diff --git a/test/fixtures/expected/tint-red.jpg b/test/fixtures/expected/tint-red.jpg index ee72cbab6..a719c706c 100644 Binary files a/test/fixtures/expected/tint-red.jpg and b/test/fixtures/expected/tint-red.jpg differ diff --git a/test/fixtures/expected/tint-sepia.jpg b/test/fixtures/expected/tint-sepia.jpg index 3c8af2c51..b2ea936d4 100644 Binary files a/test/fixtures/expected/tint-sepia.jpg and b/test/fixtures/expected/tint-sepia.jpg differ diff --git a/test/unit/tint.js b/test/unit/tint.js index 4c5d6e01c..19f4ae2db 100644 --- a/test/unit/tint.js +++ b/test/unit/tint.js @@ -8,16 +8,19 @@ const assert = require('assert'); const sharp = require('../../'); const fixtures = require('../fixtures'); +// Allow for small rounding differences between platforms +const maxDistance = 6; + describe('Tint', function () { it('tints rgb image red', function (done) { const output = fixtures.path('output.tint-red.jpg'); sharp(fixtures.inputJpg) - .resize(320, 240, { fastShrinkOnLoad: false }) + .resize(320, 240) .tint('#FF0000') .toFile(output, function (err, info) { if (err) throw err; assert.strictEqual(true, info.size > 0); - fixtures.assertMaxColourDistance(output, fixtures.expected('tint-red.jpg'), 18); + fixtures.assertMaxColourDistance(output, fixtures.expected('tint-red.jpg'), maxDistance); done(); }); }); @@ -25,12 +28,12 @@ describe('Tint', function () { it('tints rgb image green', function (done) { const output = fixtures.path('output.tint-green.jpg'); sharp(fixtures.inputJpg) - .resize(320, 240, { fastShrinkOnLoad: false }) + .resize(320, 240) .tint('#00FF00') .toFile(output, function (err, info) { if (err) throw err; assert.strictEqual(true, info.size > 0); - fixtures.assertMaxColourDistance(output, fixtures.expected('tint-green.jpg'), 27); + fixtures.assertMaxColourDistance(output, fixtures.expected('tint-green.jpg'), maxDistance); done(); }); }); @@ -38,12 +41,12 @@ describe('Tint', function () { it('tints rgb image blue', function (done) { const output = fixtures.path('output.tint-blue.jpg'); sharp(fixtures.inputJpg) - .resize(320, 240, { fastShrinkOnLoad: false }) + .resize(320, 240) .tint('#0000FF') .toFile(output, function (err, info) { if (err) throw err; assert.strictEqual(true, info.size > 0); - fixtures.assertMaxColourDistance(output, fixtures.expected('tint-blue.jpg'), 14); + fixtures.assertMaxColourDistance(output, fixtures.expected('tint-blue.jpg'), maxDistance); done(); }); }); @@ -51,13 +54,13 @@ describe('Tint', function () { it('tints rgb image with sepia tone', function (done) { const output = fixtures.path('output.tint-sepia-hex.jpg'); sharp(fixtures.inputJpg) - .resize(320, 240, { fastShrinkOnLoad: false }) + .resize(320, 240) .tint('#704214') .toFile(output, function (err, info) { if (err) throw err; assert.strictEqual(320, info.width); assert.strictEqual(240, info.height); - fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), 10); + fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), maxDistance); done(); }); }); @@ -65,13 +68,13 @@ describe('Tint', function () { it('tints rgb image with sepia tone with rgb colour', function (done) { const output = fixtures.path('output.tint-sepia-rgb.jpg'); sharp(fixtures.inputJpg) - .resize(320, 240, { fastShrinkOnLoad: false }) + .resize(320, 240) .tint([112, 66, 20]) .toFile(output, function (err, info) { if (err) throw err; assert.strictEqual(320, info.width); assert.strictEqual(240, info.height); - fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), 10); + fixtures.assertMaxColourDistance(output, fixtures.expected('tint-sepia.jpg'), maxDistance); done(); }); }); @@ -79,13 +82,13 @@ describe('Tint', function () { it('tints rgb image with alpha channel', function (done) { const output = fixtures.path('output.tint-alpha.png'); sharp(fixtures.inputPngRGBWithAlpha) - .resize(320, 240, { fastShrinkOnLoad: false }) + .resize(320, 240) .tint('#704214') .toFile(output, function (err, info) { if (err) throw err; assert.strictEqual(320, info.width); assert.strictEqual(240, info.height); - fixtures.assertMaxColourDistance(output, fixtures.expected('tint-alpha.png'), 10); + fixtures.assertMaxColourDistance(output, fixtures.expected('tint-alpha.png'), maxDistance); done(); }); }); @@ -93,12 +96,12 @@ describe('Tint', function () { it('tints cmyk image red', function (done) { const output = fixtures.path('output.tint-cmyk.jpg'); sharp(fixtures.inputJpgWithCmykProfile) - .resize(320, 240, { fastShrinkOnLoad: false }) + .resize(320, 240) .tint('#FF0000') .toFile(output, function (err, info) { if (err) throw err; assert.strictEqual(true, info.size > 0); - fixtures.assertMaxColourDistance(output, fixtures.expected('tint-cmyk.jpg'), 15); + fixtures.assertMaxColourDistance(output, fixtures.expected('tint-cmyk.jpg'), maxDistance); done(); }); });