From 0bd1715f362a20207fcd7efbac81adf7b0986ced Mon Sep 17 00:00:00 2001 From: Lovell Fuller Date: Sat, 4 Nov 2023 14:09:50 +0000 Subject: [PATCH] Options for trim op must be an Object, add lineArt #2363 --- docs/api-resize.md | 47 ++++++++++---------- docs/changelog.md | 3 ++ docs/search-index.json | 2 +- lib/constructor.js | 3 +- lib/index.d.ts | 10 +++-- lib/resize.js | 87 ++++++++++++++++++-------------------- src/operations.cc | 4 +- src/operations.h | 2 +- src/pipeline.cc | 10 ++--- src/pipeline.h | 4 +- test/types/sharp.test-d.ts | 4 +- test/unit/trim.js | 67 ++++++++++++----------------- 12 files changed, 118 insertions(+), 125 deletions(-) diff --git a/docs/api-resize.md b/docs/api-resize.md index 5b84b1e3d..6dc78ead1 100644 --- a/docs/api-resize.md +++ b/docs/api-resize.md @@ -251,7 +251,7 @@ sharp(input) ## trim -> trim(trim) ⇒ Sharp +> trim([options]) ⇒ Sharp Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. @@ -259,8 +259,7 @@ Images with an alpha channel will use the combined bounding box of alpha and non If the result of this operation would trim an image to nothing then no change is made. -The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`, -will contain `trimOffsetLeft` and `trimOffsetTop` properties. +The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties. **Throws**: @@ -270,46 +269,44 @@ will contain `trimOffsetLeft` and `trimOffsetTop` properties. | Param | Type | Default | Description | | --- | --- | --- | --- | -| trim | string \| number \| Object | | the specific background colour to trim, the threshold for doing so or an Object with both. | -| [trim.background] | string \| Object | "'top-left pixel'" | background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. | -| [trim.threshold] | number | 10 | the allowed difference from the above colour, a positive number. | +| [options] | Object | | | +| [options.background] | string \| Object | "'top-left pixel'" | Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. | +| [options.threshold] | number | 10 | Allowed difference from the above colour, a positive number. | +| [options.lineArt] | boolean | false | Does the input more closely resemble line art (e.g. vector) rather than being photographic? | **Example** ```js // Trim pixels with a colour similar to that of the top-left pixel. -sharp(input) +await sharp(input) .trim() - .toFile(output, function(err, info) { - ... - }); + .toFile(output); ``` **Example** ```js // Trim pixels with the exact same colour as that of the top-left pixel. -sharp(input) - .trim(0) - .toFile(output, function(err, info) { - ... - }); +await sharp(input) + .trim({ + threshold: 0 + }) + .toFile(output); ``` **Example** ```js -// Trim only pixels with a similar colour to red. -sharp(input) - .trim("#FF0000") - .toFile(output, function(err, info) { - ... - }); +// Assume input is line art and trim only pixels with a similar colour to red. +const output = await sharp(input) + .trim({ + background: "#FF0000", + lineArt: true + }) + .toBuffer(); ``` **Example** ```js // Trim all "yellow-ish" pixels, being more lenient with the higher threshold. -sharp(input) +const output = await sharp(input) .trim({ background: "yellow", threshold: 42, }) - .toFile(output, function(err, info) { - ... - }); + .toBuffer(); ``` \ No newline at end of file diff --git a/docs/changelog.md b/docs/changelog.md index 890fd344d..870c75590 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -14,6 +14,9 @@ Requires libvips v8.15.0 * Remove `sharp.vendor`. +* Options for `trim` operation must be an Object, add new `lineArt` option. + [#2363](https://github.com/lovell/sharp/issues/2363) + * 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 a8c3bc16b..5386316c8 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 x64 glibc 2.26, musl 1.2.2, CPU with SSE4.2 Linux ARM64 glibc 2.26, musl 1","k":"prebuilt binaries compiled libvips common platforms macos arm linux glibc musl cpu sse","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":"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":"Worker threads","d":"On some platforms, including glibc-based Linux, the main thread must call requiresharp _before_ worker threads are created. This is to ensure shared libraries remain loaded in memory until after all t","k":"worker threads platforms glibc linux main thread shared libraries remain loaded memory","l":"/install#worker-threads"},{"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","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 x64 glibc 2.26, musl 1.2.2, CPU with SSE4.2 Linux ARM64 glibc 2.26, musl 1","k":"prebuilt binaries compiled libvips common platforms macos arm linux glibc musl cpu sse","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":"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":"Worker threads","d":"On some platforms, including glibc-based Linux, the main thread must call requiresharp _before_ worker threads are created. This is to ensure shared libraries remain loaded in memory until after all t","k":"worker threads platforms glibc linux main thread shared libraries remain loaded memory","l":"/install#worker-threads"},{"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 diff --git a/lib/constructor.js b/lib/constructor.js index cb08cc134..95fd0729a 100644 --- a/lib/constructor.js +++ b/lib/constructor.js @@ -230,7 +230,8 @@ const Sharp = function (input, options) { threshold: 0, thresholdGrayscale: true, trimBackground: [], - trimThreshold: 0, + trimThreshold: -1, + trimLineArt: false, gamma: 0, gammaOut: 0, greyscale: false, diff --git a/lib/index.d.ts b/lib/index.d.ts index 863aff11a..a781180c7 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -847,11 +847,11 @@ declare namespace sharp { * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. * The info response Object will contain trimOffsetLeft and trimOffsetTop properties. - * @param trim The specific background colour to trim, the threshold for doing so or an Object with both. + * @param options trim options * @throws {Error} Invalid parameters * @returns A sharp instance that can be used to chain operations */ - trim(trim?: string | number | TrimOptions): Sharp; + trim(options?: TrimOptions): Sharp; //#endregion } @@ -1342,10 +1342,12 @@ declare namespace sharp { } interface TrimOptions { - /** background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */ + /** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */ background?: Color | undefined; - /** the allowed difference from the above colour, a positive number. (optional, default `10`) */ + /** Allowed difference from the above colour, a positive number. (optional, default 10) */ threshold?: number | undefined; + /** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */ + lineArt?: boolean | undefined; } interface RawOptions { diff --git a/lib/resize.js b/lib/resize.js index e5e3b1462..e4fcdd616 100644 --- a/lib/resize.js +++ b/lib/resize.js @@ -494,70 +494,67 @@ function extract (options) { * * If the result of this operation would trim an image to nothing then no change is made. * - * The `info` response Object, obtained from callback of `.toFile()` or `.toBuffer()`, - * will contain `trimOffsetLeft` and `trimOffsetTop` properties. + * The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties. * * @example * // Trim pixels with a colour similar to that of the top-left pixel. - * sharp(input) + * await sharp(input) * .trim() - * .toFile(output, function(err, info) { - * ... - * }); + * .toFile(output); + * * @example * // Trim pixels with the exact same colour as that of the top-left pixel. - * sharp(input) - * .trim(0) - * .toFile(output, function(err, info) { - * ... - * }); + * await sharp(input) + * .trim({ + * threshold: 0 + * }) + * .toFile(output); + * * @example - * // Trim only pixels with a similar colour to red. - * sharp(input) - * .trim("#FF0000") - * .toFile(output, function(err, info) { - * ... - * }); + * // Assume input is line art and trim only pixels with a similar colour to red. + * const output = await sharp(input) + * .trim({ + * background: "#FF0000", + * lineArt: true + * }) + * .toBuffer(); + * * @example * // Trim all "yellow-ish" pixels, being more lenient with the higher threshold. - * sharp(input) + * const output = await sharp(input) * .trim({ * background: "yellow", * threshold: 42, * }) - * .toFile(output, function(err, info) { - * ... - * }); + * .toBuffer(); * - * @param {string|number|Object} trim - the specific background colour to trim, the threshold for doing so or an Object with both. - * @param {string|Object} [trim.background='top-left pixel'] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. - * @param {number} [trim.threshold=10] - the allowed difference from the above colour, a positive number. + * @param {Object} [options] + * @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. + * @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number. + * @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic? * @returns {Sharp} * @throws {Error} Invalid parameters */ -function trim (trim) { - if (!is.defined(trim)) { - this.options.trimThreshold = 10; - } else if (is.string(trim)) { - this._setBackgroundColourOption('trimBackground', trim); - this.options.trimThreshold = 10; - } else if (is.number(trim)) { - if (trim >= 0) { - this.options.trimThreshold = trim; - } else { - throw is.invalidParameterError('threshold', 'positive number', trim); - } - } else if (is.object(trim)) { - this._setBackgroundColourOption('trimBackground', trim.background); - if (!is.defined(trim.threshold)) { - this.options.trimThreshold = 10; - } else if (is.number(trim.threshold) && trim.threshold >= 0) { - this.options.trimThreshold = trim.threshold; +function trim (options) { + this.options.trimThreshold = 10; + if (is.defined(options)) { + if (is.object(options)) { + if (is.defined(options.background)) { + this._setBackgroundColourOption('trimBackground', options.background); + } + if (is.defined(options.threshold)) { + if (is.number(options.threshold) && options.threshold >= 0) { + this.options.trimThreshold = options.threshold; + } else { + throw is.invalidParameterError('threshold', 'positive number', options.threshold); + } + } + if (is.defined(options.lineArt)) { + this._setBooleanOption('trimLineArt', options.lineArt); + } } else { - throw is.invalidParameterError('threshold', 'positive number', trim); + throw is.invalidParameterError('trim', 'object', options); } - } else { - throw is.invalidParameterError('trim', 'string, number or object', trim); } if (isRotationExpected(this.options)) { this.options.rotateBeforePreExtract = true; diff --git a/src/operations.cc b/src/operations.cc index 3c95dac5b..e14739013 100644 --- a/src/operations.cc +++ b/src/operations.cc @@ -265,7 +265,7 @@ namespace sharp { /* Trim an image */ - VImage Trim(VImage image, std::vector background, double threshold) { + VImage Trim(VImage image, std::vector background, double threshold, bool const lineArt) { if (image.width() < 3 && image.height() < 3) { throw VError("Image to trim must be at least 3x3 pixels"); } @@ -287,6 +287,7 @@ namespace sharp { int left, top, width, height; left = image.find_trim(&top, &width, &height, VImage::option() ->set("background", background) + ->set("line_art", lineArt) ->set("threshold", threshold)); if (HasAlpha(image)) { // Search alpha channel (A) @@ -294,6 +295,7 @@ namespace sharp { VImage alpha = image[image.bands() - 1]; leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option() ->set("background", backgroundAlpha) + ->set("line_art", lineArt) ->set("threshold", threshold)); if (widthA > 0 && heightA > 0) { if (width > 0 && height > 0) { diff --git a/src/operations.h b/src/operations.h index 10a0c6ced..6e5b82d48 100644 --- a/src/operations.h +++ b/src/operations.h @@ -79,7 +79,7 @@ namespace sharp { /* Trim an image */ - VImage Trim(VImage image, std::vector background, double const threshold); + VImage Trim(VImage image, std::vector background, double threshold, bool const lineArt); /* * Linear adjustment (a * in + b) diff --git a/src/pipeline.cc b/src/pipeline.cc index ccc74fc3b..05a2de323 100644 --- a/src/pipeline.cc +++ b/src/pipeline.cc @@ -126,10 +126,10 @@ class PipelineWorker : public Napi::AsyncWorker { } // Trim - if (baton->trimThreshold > 0.0) { + if (baton->trimThreshold >= 0.0) { MultiPageUnsupported(nPages, "Trim"); image = sharp::StaySequential(image, access); - image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold); + image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold, baton->trimLineArt); baton->trimOffsetLeft = image.xoffset(); baton->trimOffsetTop = image.yoffset(); } @@ -182,7 +182,7 @@ class PipelineWorker : public Napi::AsyncWorker { // - trimming or pre-resize extract isn't required; // - input colourspace is not specified; bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) && - baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold == 0.0 && + baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold < 0.0 && baton->colourspaceInput == VIPS_INTERPRETATION_LAST && !shouldRotateBefore; if (shouldPreShrink) { @@ -1248,11 +1248,10 @@ class PipelineWorker : public Napi::AsyncWorker { info.Set("attentionX", static_cast(baton->attentionX)); info.Set("attentionY", static_cast(baton->attentionY)); } - if (baton->trimThreshold > 0.0) { + if (baton->trimThreshold >= 0.0) { info.Set("trimOffsetLeft", static_cast(baton->trimOffsetLeft)); info.Set("trimOffsetTop", static_cast(baton->trimOffsetTop)); } - if (baton->input->textAutofitDpi) { info.Set("textAutofitDpi", static_cast(baton->input->textAutofitDpi)); } @@ -1519,6 +1518,7 @@ Napi::Value pipeline(const Napi::CallbackInfo& info) { baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale"); baton->trimBackground = sharp::AttrAsVectorOfDouble(options, "trimBackground"); baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold"); + baton->trimLineArt = sharp::AttrAsBool(options, "trimLineArt"); baton->gamma = sharp::AttrAsDouble(options, "gamma"); baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut"); baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA"); diff --git a/src/pipeline.h b/src/pipeline.h index ce7703d7d..86167e6e3 100644 --- a/src/pipeline.h +++ b/src/pipeline.h @@ -92,6 +92,7 @@ struct PipelineBaton { bool thresholdGrayscale; std::vector trimBackground; double trimThreshold; + bool trimLineArt; int trimOffsetLeft; int trimOffsetTop; std::vector linearA; @@ -260,7 +261,8 @@ struct PipelineBaton { threshold(0), thresholdGrayscale(true), trimBackground{}, - trimThreshold(0.0), + trimThreshold(-1.0), + trimLineArt(false), trimOffsetLeft(0), trimOffsetTop(0), linearA{}, diff --git a/test/types/sharp.test-d.ts b/test/types/sharp.test-d.ts index 38f34171b..2d6804c25 100644 --- a/test/types/sharp.test-d.ts +++ b/test/types/sharp.test-d.ts @@ -572,8 +572,8 @@ const nohalo: string = sharp.interpolators.nohalo; const vertexSplitQuadraticBasisSpline: string = sharp.interpolators.vertexSplitQuadraticBasisSpline; // Triming -sharp(input).trim('#000').toBuffer(); -sharp(input).trim(10).toBuffer(); +sharp(input).trim({ background: '#000' }).toBuffer(); +sharp(input).trim({ threshold: 10, lineArt: true }).toBuffer(); sharp(input).trim({ background: '#bf1942', threshold: 30 }).toBuffer(); // Text input diff --git a/test/unit/trim.js b/test/unit/trim.js index 8d2c76d44..aa559d5a8 100644 --- a/test/unit/trim.js +++ b/test/unit/trim.js @@ -46,7 +46,9 @@ describe('Trim borders', function () { it('16-bit PNG with alpha channel', function (done) { sharp(fixtures.inputPngWithTransparency16bit) .resize(32, 32) - .trim(20) + .trim({ + threshold: 20 + }) .toBuffer(function (err, data, info) { if (err) throw err; assert.strictEqual(true, data.length > 0); @@ -96,7 +98,9 @@ describe('Trim borders', function () { .then(rotated30 => sharp(rotated30) .rotate(-30) - .trim(128) + .trim({ + threshold: 128 + }) .toBuffer({ resolveWithObject: true }) .then(({ info }) => { assert.strictEqual(20, info.width); @@ -198,49 +202,26 @@ describe('Trim borders', function () { assert.strictEqual(trimOffsetLeft, 0); }); - describe('Valid parameters', function () { - const expected = fixtures.expected('alpha-layer-1-fill-trim-resize.png'); - Object.entries({ - 'Background and threshold default': undefined, - 'Background string': '#00000000', - 'Background option': { - background: '#00000000' - }, - 'Threshold number': 10, - 'Threshold option': { - threshold: 10 - } - }).forEach(function ([description, parameter]) { - it(description, function (done) { - sharp(fixtures.inputPngOverlayLayer1) - .resize(450, 322) - .trim(parameter) - .toBuffer(function (err, data, info) { - if (err) throw err; - assert.strictEqual('png', info.format); - assert.strictEqual(450, info.width); - assert.strictEqual(322, info.height); - assert.strictEqual(-204, info.trimOffsetLeft); - assert.strictEqual(0, info.trimOffsetTop); - fixtures.assertSimilar(expected, data, done); - }); - }); - }); + it('Works with line-art', async () => { + const { info } = await sharp(fixtures.inputJpgOverlayLayer2) + .trim({ lineArt: true }) + .toBuffer({ resolveWithObject: true }); + + assert.strictEqual(info.trimOffsetTop, -552); }); describe('Invalid parameters', function () { Object.entries({ - 'Invalid background string': 'fail', + 'Invalid string': 'fail', 'Invalid background option': { background: 'fail' }, - - 'Negative threshold number': -1, 'Negative threshold option': { threshold: -1 }, - - Boolean: false + 'Invalid lineArt': { + lineArt: 'fail' + } }).forEach(function ([description, parameter]) { it(description, function () { assert.throws(function () { @@ -253,7 +234,9 @@ describe('Trim borders', function () { describe('Specific background colour', function () { it('Doesn\'t trim at all', async () => { const { info } = await sharp(fixtures.inputPngTrimSpecificColour) - .trim('yellow') + .trim({ + background: 'yellow' + }) .toBuffer({ resolveWithObject: true }); const { width, height, trimOffsetTop, trimOffsetLeft } = info; @@ -265,7 +248,9 @@ describe('Trim borders', function () { it('Only trims the bottom', async () => { const { info } = await sharp(fixtures.inputPngTrimSpecificColour) - .trim('#21468B') + .trim({ + background: '#21468B' + }) .toBuffer({ resolveWithObject: true }); const { width, height, trimOffsetTop, trimOffsetLeft } = info; @@ -277,7 +262,9 @@ describe('Trim borders', function () { it('Only trims the bottom, in 16-bit', async () => { const { info } = await sharp(fixtures.inputPngTrimSpecificColour16bit) - .trim('#21468B') + .trim({ + background: '#21468B' + }) .toBuffer({ resolveWithObject: true }); const { width, height, trimOffsetTop, trimOffsetLeft } = info; @@ -289,7 +276,9 @@ describe('Trim borders', function () { it('Only trims the bottom, including alpha', async () => { const { info } = await sharp(fixtures.inputPngTrimSpecificColourIncludeAlpha) - .trim('#21468B80') + .trim({ + background: '#21468B80' + }) .toBuffer({ resolveWithObject: true }); const { width, height, trimOffsetTop, trimOffsetLeft } = info;