Giter VIP home page Giter VIP logo

sharp-cli's Introduction

sharp-cli

CLI for sharp, a high performance Node.js image processing module.

Install

$ npm install sharp-cli

Usage

sharp <options> [command..]

Commands:
  sharp affine <matrix..>                      Perform an affine transform on an image
  sharp bandbool <operator>                    Perform a bitwise boolean operation on all input
                                               image channels (bands) to produce a single channel
                                               output image
  sharp blur [sigma]                           Blur the image
  sharp boolean <operand> <operator>           Perform a bitwise boolean operation with operand
                                               image
  sharp clahe <width> <height>                 Perform contrast limiting adaptive histogram
                                               equalization CLAHE
  sharp composite [images..]                   Composite image(s) over the processed (resized,
                                               extracted etc.) image
  sharp convolve <width> <height> <kernel..>   Convolve the image with the specified kernel
  sharp ensureAlpha [alpha]                    Ensure the output image has an alpha transparency
                                               channel
  sharp extend <top> <bottom> <left> <right>   Extends/pads the edges of the image with the provided
                                               background colour
  sharp extract <top> <left> <width> <height>  Extract a region of the image
  sharp extractChannel <channel>               Extract a single channel from a multi-channel image
  sharp flatten [background]                   Merge alpha transparency channel, if any, with a
                                               background
  sharp flip                                   Flip the image about the vertical Y axis
  sharp flop                                   Flop the image about the horizontal X axis
  sharp gamma [gamma] [gammaOut]               Apply a gamma correction by reducing the encoding
                                               (darken) pre-resize then increasing the encoding
                                               (brighten) post-resize
  sharp greyscale                              Convert to 8-bit greyscale; 256 shades of grey
                                                                                [aliases: grayscale]
  sharp joinChannel <images..>                 Join one or more channels to the image
  sharp linear [multiplier..]                  Apply the linear formula a × input + b to the image
                                               to adjust image levels
  sharp median [size]                          Apply median filter
  sharp modulate                               Transforms the image using brightness, saturation,
                                               hue rotation, and lightness
  sharp negate                                 Produce the "negative" of the image
  sharp normalise                              Enhance output image contrast by stretching its
                                               luminance to cover the full dynamic range
                                                                                [aliases: normalize]
  sharp pipelineColourspace <colourspace>      Set the pipeline colourspace
                                                                       [aliases: pipelineColorspace]
  sharp recomb <matrix..>                      Recomb the image with the specified matrix
  sharp removeAlpha                            Remove alpha channel, if any
  sharp resize [width] [height]                Resize image to width, height, or width × height
  sharp rotate [angle]                         Rotate the output image
  sharp sharpen [sigma]                        Sharpen the image
  sharp threshold [value]                      Any pixel value greather than or equal to the
                                               threshold value will be set to 255, otherwise it will
                                               be set to 0
  sharp tint <rgb>                             Tint the image using the provided chroma while
                                               preserving the image luminance
  sharp tile [size]                            Use tile-based deep zoom (image pyramid) output
  sharp toColourspace <colourspace>            Set the output colourspace    [aliases: toColorspace]
  sharp trim [threshold]                       Trim pixels from all edges that contain values
                                               similar to the given background color, which defaults
                                               to that of the top-left pixel
  sharp unflatten                              Ensure the image has an alpha channel with all white
                                               pixel values made fully transparent

Global Options
  -i, --input    Path to (an) image file(s)                      [array] [required] [default: stdin]
  -o, --output   Directory or URI template to write the image files to
                                                               [string] [required] [default: stdout]
      --timeout  Number of seconds after which processing will be stopped                   [number]

Input Options
      --animated          Read all frames/pages of an animated image                       [boolean]
      --failOn            Level of sensitivity to invalid images
                               [choices: "none", "truncated", "error", "warning"] [default: warning]
      --density           DPI for vector images                               [number] [default: 72]
      --ignoreIcc         Should the embedded ICC profile, if any, be ignored
                                                                          [boolean] [default: false]
      --level             Level to extract from a multi-level input (OpenSlide), zero based [number]
      --limitInputPixels  Do not process input images where the number of pixels (width x height)
                          exceeds this limit                           [number] [default: 268402689]
      --page              Page number to start extracting from for multi-page input         [number]
      --pages             Number of pages to extract for multi-page input      [number] [default: 1]
      --sequentialRead    Use sequential rather than random access where possible
                                                                          [boolean] [default: false]
      --subifd            subIFD to extract for OME-TIFF                      [number] [default: -1]
      --unlimited         Remove safety features that help prevent memory exhaustion       [boolean]

Output Options
  -c, --compressionLevel          zlib compression level                       [number] [default: 6]
  -f, --format                    Force output to a given format
      [choices: "avif", "gif", "heif", "jpeg", "jpg", "png", "raw", "tiff", "webp"] [default: input]
  -m, --metadata, --withMetadata  Include all metadata (EXIF, XMP, IPTC) from the input image in the
                                  output image                                             [boolean]
      --metadata.density          Number of pixels per inch (DPI)                           [number]
      --metadata.exif             Object keyed by IFD0, IFD1 etc. of key/value string pairs to write
                                  as EXIF data                                         [default: {}]
      --metadata.icc              Filesystem path to output ICC profile     [string] [default: sRGB]
      --metadata.orientation      Used to update the EXIF Orientation tag                   [number]
  -p, --progressive               Use progressive (interlace) scan                         [boolean]
  -q, --quality                   Quality                                     [number] [default: 80]

Optimization Options
      --adaptiveFiltering                       Use adaptive row filtering                 [boolean]
      --alphaQuality                            Quality of alpha layer        [number] [default: 80]
      --bitdepth                                Squash 8-bit images down to 1, 2, or 4 bit
                                                                  [choices: 1, 2, 4, 8] [default: 8]
      --chromaSubsampling                       Set to "4:4:4" to prevent chroma subsampling when
                                                quality <= 90
                                                            [string] [default: 4:4:4 (AVIF) / 4:2:0]
      --colors, --colours                       Maximum number of palette entries
                                                                             [number] [default: 256]
      --compression                             Compression options
        [choices: "ccittfax4", "deflate", "jpeg", "jp2k", "lzw", "none", "packbits", "webp", "zstd"]
                                                                                   [default: "jpeg"]
      --delay                                   Delay(s) between animation frames           [number]
      --dither                                  Level of Floyd-Steinberg error diffusion
                                                                             [number] [default: 1.0]
      --effort                                  Level of CPU effort to reduce file size
                                                                [number] [default: 7 (GIF, PNG) / 4]
      --hcompression                            Compression format
                                                           [choices: "hevc", "av1"] [default: "av1"]
      --interFrameMaxError                      Maximum inter-frame error for transparency  [number]
      --interPaletteMaxError                    Maximum inter-palette error for palette reuse
                                                                                            [number]
      --loop                                    Number of animation iterations [number] [default: 0]
      --lossless                                Use lossless compression mode              [boolean]
      --minSize                                 Prevent use of animation key frames to minimize file
                                                size                                       [boolean]
      --mixed                                   Allow mixture of lossy and lossless animation frames
                                                                                           [boolean]
      --mozjpeg                                 Use mozjpeg defaults                       [boolean]
      --nearLossless                            Use near_lossless compression mode         [boolean]
      --optimise, --optimize                    Apply optimiseScans, overshootDeringing, and
                                                trellisQuantisation                        [boolean]
      --optimiseCoding, --optimizeCoding        Optimise Huffman coding tables
                                                                           [boolean] [default: true]
      --optimiseScans, --optimizeScans          Optimise progressive scans                 [boolean]
      --overshootDeringing                      Apply overshoot deringing                  [boolean]
      --palette                                 Quantise to a palette-based image with alpha
                                                transparency support                       [boolean]
      --predictor                               Compression predictor
                                    [choices: "float", "horizontal", "none"] [default: "horizontal"]
      --preset                                  Named preset for preprocessing/filtering
            [choices: "default", "photo", "picture", "drawing", "icon", "text"] [default: "default"]
      --pyramid                                 Write an image pyramid                     [boolean]
      --quantisationTable, --quantizationTable  Quantization table to use      [number] [default: 0]
      --reuse, --reoptimise, --reoptimize       Always generate new palettes (slow)        [boolean]
      --resolutionUnit                          Resolution unit
                                                             [choices: "cm", "inch"] [default: inch]
      --smartSubsample                          High quality chroma subsampling            [boolean]
      --tileBackground                          Background colour, parsed by the color module
                                                          [string] [default: rgba(255, 255, 255, 1)]
      --tileHeight                              Vertical tile size                          [number]
      --tileWidth                               Horizontal tile size                        [number]
      --trellisQuantisation                     Apply trellis quantisation                 [boolean]
      --xres                                    Horizontal resolution        [number] [default: 1.0]
      --yres                                    Vertical resolution          [number] [default: 1.0]

Misc. Options
  -h, --help     Show help                                                                 [boolean]
  -v, --version  Show version number                                                       [boolean]

Examples:
  sharp -i ./input.jpg -o ./out resize 300 200        out/input.jpg will be a 300 pixels wide and
                                                      200 pixels high image containing a scaled and
                                                      cropped version of input.jpg
  sharp -i ./input.jpg -o ./out -mq90 rotate 180 --   out/input.jpg will be an upside down, 300px
  resize 300 -- flatten "#ff6600" -- composite        wide, alpha channel flattened onto orange
  ./overlay.png --gravity southeast -- sharpen        background, composited with overlay.png with
                                                      SE gravity, sharpened, with metadata, 90%
                                                      quality version of input.jpg
  sharp -i ./input.jpg -o ./out --metadata            Include all metadata in the output image
  sharp -i ./input.jpg -o ./out                       Set "IFD0-Copyright" in output EXIF metadata
  --metadata.exif.IFD0.Copyright "Wernham Hogg"
  sharp -i ./input.jpg -o ./out --metadata.density    Set output metadata to 96 DPI
  96

For more information on available options, please visit https://sharp.pixelplumbing.com/

Input and output

  • The CLI supports input streams.
  • Glob patterns are allowed, for example --input './images/**/*.jpg'. Make sure you quote the pattern when using the CLI.
  • Supported output macros: {root}, {dir}, {base}, {name}, and {ext} (from Node.js path), for example: --output {dir} will overwrite original files.
┌─────────────────────┬────────────┐
│          dir        │    base    │
├──────┬              ├──────┬─────┤
│ root │              │ name │ ext │
"  /    home/user/dir / file  .txt "
└──────┴──────────────┴──────┴─────┘

Related

  • sharp - API for this module

Changelog

See the Changelog for a list of changes.

License

The MIT License (MIT)

Copyright (c) 2019 Mark van Seventer

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

sharp-cli's People

Contributors

lovell avatar mubaidr avatar vseventer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

sharp-cli's Issues

Resize not working without a non-option argument contradicting official example

Running sharp resize --help gives me as the first example:

Examples:
  sharp resize --height 100                 The output will be 100 pixels high,
                                            auto-scaled width

However, if I try this like sharp resize --height 100 -i input.jpg -o output.jpg, I get:

Not enough non-option arguments: got 0, need at least 1

Specify --help for available options

Either the example should be removed or resize should also work without non-option arguments. Personally, I'd prefer the latter.

Overwriting the input files failes in Node v16.4.1

sharp resize 100 --input '*.png' --output '{dir}'

works in Node v14.17.2 but fails in Node v16.4.1 with the following error message:

The value of "position" is out of range. It must be an integer. Received Infinity

By inserting logger.error(err.stack) in index.js, I got the following stack trace:

RangeError [ERR_OUT_OF_RANGE]: The value of "position" is out of range. It must be an integer. Received Infinity
    at read (node:fs:653:3)
    at node:internal/util:335:7
    at new Promise (<anonymous>)
    at read (node:internal/util:321:12)
    at Readable.read [as _read] (/[…]/sharp-cli/node_modules/rw-stream/index.js:43:39)
    at Readable.read (node:internal/streams/readable:483:10)
    at resume_ (node:internal/streams/readable:981:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

Unexpected token

I'm getting an error when using the tool. Does the tool work on windows?

λ sharp -i ./1.png -o ./out resize 300 200
C:\Users\sblowes\AppData\Roaming\npm\node_modules\sharp-cli\lib\index.js:35
module.exports = (argv, options = { }) => {
                                ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:54:16)
    at Module._compile (module.js:375:25)
    at Object.Module._extensions..js (module.js:406:10)
    at Module.load (module.js:345:32)
    at Function.Module._load (module.js:302:12)
    at Module.require (module.js:355:17)
    at require (internal/module.js:13:17)
    at Object.<anonymous> (C:\Users\sblowes\AppData\Roaming\npm\node_modules\sharp-cli\bin\cli.js:29:1)
    at Module._compile (module.js:399:26)
    at Object.Module._extensions..js (module.js:406:10)

Alpha channel is removed

Putting this image through sharp-cli makes the semi-transparent pixels opaque, or a least a lot less transparent.

I have tried adding --alphaQuality 100 and --quality 100 to the command, but that doesn't help.

(I hope I am reporting this issue the correct place. This is the original issue that I have: expo/expo-cli#1373.)

Question

Hi,
I need to resize an image with 2048px maximum hight or 2048px maximum width.
How to do this with command line?

Usage on Windows

Hello, i have one more question regarding Windows. I have Node 6 here, but i cannot manage how to use the cli properly. The point is, that it creates the new image in the same folder, and NOT uses the folder path i passed as "-o" parameter. See my output:

Admin@DESKTOP-RLI0V1T MINGW64 /d/Site/maerchen (master)
$ sharp -i ./static/images/* -o ./out resize 1500 0
D:%5CSite%5Cmaerchen%5Cout
D:%5CSite%5Cmaerchen%5Cout

So it's creating new files with wrong names in folder where i stand.
I have tried using the "Git Bash" and "Cmder". Result is the same.

Would someone have a hint for me?

CPU usage low...

Today i found https://sharp.pixelplumbing.com/ and after reading i found your cli version. I am impressed by the results, it works great. Now i am running it on thousands of images and i wonder why it does not use the full power of my 16 cores 5950x. Load in htop looks pretty low. Is there anything i could do?
I found no switch to set a core-count, or something.

Regards.
Not sure if its an "issue"...

document how to optimize a whole tree

It appears that sharp-cli is embedding url-template that allow to use pattern matching in its command line.

It would be great to document that in the README file so that one can discover how to optimize a whole tree hierarchy.

Imagine there is the following tree:

directory/
directory/subdir1
directory/subdir1/image1.jpg
directory/subdir2
directory/subdir2/image2.png

I want to use a command that looks like npx sharp-cli resize 800 800 --format input --fit inside --input ./directory/**/*.{jpg|png} --output ./directory/ so that all jpg and png images are optimized and resized (if too big).

I found that url-template documentation is much too light and does not give much information about available variables.

@vseventer proposed something like --output "{dir}/{base}" but I could not succeed to make it work.

Support for composite multiple images

How to composite multiple images by a single command? I'm making a PHP SDK for Sharp using this project so maybe we need a solution for composite multiple images like Imagick.

npm installation directory

The npm install on wrong directory

gyp WARN EACCES user "root" does not have permission to access the dev dir "/root/.node-gyp/6.0.0"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/home/pi/node_modules/sharp/.node-gyp"

should be /usr/local/lib/nod_modules/sharp/
and /usr/local/bin for node_modules/.bin

How can I target output to a dynamic subdirectory?

I have multiples subdirectories in my image directories, and I want to convert images inside these subdirectories and output the formatted files there.

I tried with the following cmd but it outputs all files in the main directory, images. Is something like this possible? Do I need to hard code subdirectories?

npx sharp --input './dist/images/**/*.jpg' --output './dist/images/' -f webp;

Support glob input patterns

What

Support glob input patterns.

Why

We need a more powerful way of matching multiple files, as right now we only support what the command line support. This came up as part of #26, where it seems the expectation that this "just works".

How

  • sharp -i '**/*.{jpg,png}': matches all JPG and PNG files in current and child directories.

"Error: Cannot find module" error on GitLab CI

I'm trying to run the following command into a GitLab CI file .gitlab-ci.yml :

npx sharp-cli resize 800 800 --withoutEnlargement true --optimise true --progressive true --withMetadata false --format input --fit inside --input $(find ./docs -name *.jpg -or -name *.png) --output "{dir}/{base}"

On my laptop, everything run well:

$ npx sharp-cli resize 800 800 --withoutEnlargement true --optimise true --progressive true --withMetadata false --format input --fit inside --input $(find ./docs -name *.jpg -or -name *.png) --output "{dir}/{base}"
info sharp Using cached /home/myuser/.npm/_libvips/libvips-8.8.1-linux-x64.tar.gz
/home/path/to/website/docs/images/photos/sejour.jpg

But inside a GitLab CI pipeline, it fails fast:

$ npx sharp-cli resize 800 800 --withoutEnlargement true --optimise true --progressive true --withMetadata false --format input --fit inside --input $(find ./docs -name *.jpg -or -name *.png) --output "{dir}/{base}"
internal/modules/cjs/loader.js:964
throw err;
^

Error: Cannot find module '/root/.npm/_npx/12/lib/node_modules/sharp-cli/node_modules/sharp/install/libvips'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:961:17)
at Function.Module._load (internal/modules/cjs/loader.js:854:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, stat '/root/.npm/_npx/12/lib/node_modules/sharp-cli/node_modules/sharp/.node-gyp/13.3.0'
gyp ERR! System Linux 4.19.0-6-amd64
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /root/.npm/_npx/12/lib/node_modules/sharp-cli/node_modules/sharp
gyp ERR! node -v v13.3.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2019-12-08T22_44_57_178Z-debug.log
Install for [ 'sharp-cli@latest' ] failed with code 1
Authenticating with credentials from /root/.docker/config.json
ERROR: Job failed: exit code 1

This error might not be specific to sharp-cli and maybe more related to GitLab CI, but maybe someone will have a suggestion, or a starting point to look from.

I do not understand why node-gyp is into the logs. Is libvips being rebuilt on CI while it is simply downloaded on my laptop?

Thanks !

Request to not normalize the output path before applying the macros

I wanted to use sharp-cli to scale images at <folder>/original/<picture>.png to folder/scaled/<picture>.png. When I used sharp resize 2000 --input "*/original/*.png" --output "{dir}/../scaled/{base}", I got the error ENOENT: no such file or directory, open 'scaled/<picture>.png' because the folder scaled doesn't exist on the project level but only in the subfolders (i.e. <folder>/scaled). (Please take all values in this example figuratively. The error message used an absolute path but I cut the prefix as it's not relevant here, etc.)

After debugging sharp-cli locally, I realized that the problem is not where the output template is processed but rather where the arguments are parsed. So apparently yargs is to blame for this. When looking at

sharp-cli/lib/cli.js

Lines 87 to 97 in cf12e80

// @see https://sharp.pixelplumbing.com/en/stable/api-output/
output: {
alias: 'o',
defaultDescription: 'stdout',
demand: IS_TEXT_TERMINAL,
desc: 'Directory or URI template to write the image files to',
group: _global,
nargs: 1,
normalize: true,
type: 'string'
},

and yarg's options documentation, it became clear that sharp-cli asks yarg to normalize the template. After removing normalize: true,, I had the behavior I wanted.

Is there any reason to ask yarg for this normalization (rather than just resolving the path after processing the template)? If not, can you remove this line upstream so that I don't have to run a custom version of sharp-cli on my computer? (If you want, I can make a PR for this.) It cannot be there for security reasons as it's still possible to leave the current working directory with --output "{dir}/../../scaled/{base}" respectively just --output "../generated/{base}".

Resize "withoutEnlargement" option not working correctly

I'm trying to resize a directory of png images, but some of the images are already below my specified width/height, resulting in them being either cropped (if --max isn't provided) or scaled up.

For example,

sharp -i src/images/*.png -o dist/images resize 640 640 --withoutEnlargement --max -- --quality 90 --optimize

results in all images being scaled up to 640, regardless of whether or not some of the images are already smaller than 640, even though I specified the --withoutEnlargement flag.

Any ideas?

Specifying quality changes PNG file format to ISO Media

Using [email protected]:

❯ file logo.png
logo.png: PNG image data, 512 x 512, 8-bit/color RGBA, non-interlaced

❯ npx sharp-cli -i ./logo.png -o ./logo_opt.png
/.../logo_opt.png

❯ file logo_opt.png
logo_opt.png: PNG image data, 512 x 512, 8-bit/color RGBA, non-interlaced

❯ file logo_opt.png
logo_opt.png: PNG image data, 512 x 512, 8-bit/color RGBA, non-interlaced

❯ npx sharp-cli -i ./logo.png -o ./logo_opt80.png --quality 80
/.../logo_opt80.png

❯ file logo_opt80.png
logo_opt80.png: ISO Media

Error when starting

sharp --help
module.js:355
  Module._extensions[extension](this, filename);
                               ^

Error: Module version mismatch. Expected 46, got 48.
    at Error (native)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/sharp-cli/node_modules/sharp/index.js:12:13)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/sharp-cli/lib/runner.js:34:15)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)````

NPM flags 3 moderate severity vulnerabilities upon install

Yaaaarg! Apologies if this is a repost, but I continue to see yargs-parser vulnerabilities in so many packages including this one. npm audit fix suggests installing sharp-cli version 1.3.0, which seems like an extreme rollback solution...

# npm audit report

yargs-parser  6.0.0 - 13.1.1
Severity: moderate
yargs-parser Vulnerable to Prototype Pollution - https://github.com/advisories/GHSA-p9pc-299p-vxgp
fix available via `npm audit fix --force`
Will install [email protected], which is a breaking change
node_modules/sharp-cli/node_modules/yargs-parser
  yargs  8.0.0-candidate.0 - 12.0.5
  Depends on vulnerable versions of yargs-parser
  node_modules/sharp-cli/node_modules/yargs
    sharp-cli  >=1.4.0
    Depends on vulnerable versions of yargs
    node_modules/sharp-cli

3 moderate severity vulnerabilities

Option to delete original?

I know you can use {dir} to overwrite the original, but that can't help if the operation is a conversion from, for example, png to jpg.

Thanks for sharing this great project!

allow to process hidden files and hidden directories

Since lasts versions and #26, sharp-cli allows to parse a whole tree and to process files in place (replacing the original file).

However, hidden files and directory are not processed are they are not parsed. They're simply ignored.

I'd love to see sharp-cli able to optimize images that are in a hidden directory.

With bash, I can set how bash behave with setting a specific shopt option:

$ shopt -u dotglob
$ ls docs/**/*.jpg
$
$ shopt -s dotglob
$ ls docs/**/*.jpg
docs/directory/.hidden-image.jpg
docs/.hidden-directory/image.jpg
$

Is there a way to set a similar option for sharp-cli? If not, could it be possible to add options to set how sharp-cli behave?

$ npx sharp-cli --include-hidden-files
$ npx sharp-cli --include-hidden-directory

Docs: document resize --fit option

Would be good to have this as example because this package is more than a wrapper and has to support / add the different options too as it seems (cmd dir).

Remove people's data from the git history

We committed our own data and some data for our friends and family. It's all gone now, but we should remove it from the git history to be safe.

We could remove the entire early history or go through one commit at a time and remove things.

unix error: Is a directory

Hi and thanks for the great cli!
I've used it before and everything was ok, but now when I'm -i ./big/* -o ./mini resize 200 I'm getting:

vips__file_open_write: unable to open file "/Users/myname/Desktop/mini" for writing
unix error: Is a directory

Am I doing something wrong?

Number specificity

Expected positive integer for width but received 1204.9586776859503 of type number

Specify --help for available options

I'm getting this error in 1.13.1 — is it because of the crazy specificity I'm passing, and it's supposed to error like this, or is this a bug? 😅 I don't think this failed in earlier versions, but I'm having problems installing older versions on my new computer...

resize but keep proportion

I want to resize a serie of images that are in a directory. I'm using the following command:

npx sharp-cli resize 800 800 --withoutEnlargement true --optimise true --progressive true --withMetadata false --format input --input *.jpg --output "out/"

Images smaller than 800x800 are just copied in the output directory.

But bigger image are resized to 800x800 (square). What I wanted is that when an image is resized, its ratio is keeped: 800x600 for a landscape, and 600x800 for a portrait.

Have I missed something?

When I have a look at the documentation, I'm not sure if I have to use a height or width parameter or not:

sharp resize [height]

--height Number of pixels wide the resultant image should be [nombre]
--width Number of pixels high the resultant image should be [nombre]

heif error from 1.11.0 on

Hi, and first of all thanks for this awesome CLI. It has sped up my thumbnailing process a TON.

There was a regression in my setup when moving from 1.10.0 to 1.11.0

This is the cmd I'm running

sharp -i media/images/site/project-gallery/tine-1/a2hlnlcafc.jpg
-o media/images/site/project-gallery/tine-1/xlarge/{name}{ext} 
--quality 85 --palette true --format jpg resize 1900 --withoutEnlargement --fit inside

It works fine on 1.10.0, but on 1.11.0 it errors with

The heif operation requires libvips to have been installed with support for libheif
Specify --help for available options

Thanks!

The documentation about the width and height of resize is confusing

sharp resize --help:

sharp resize <width> [height]

Resize image to width × height

Reading this, I would expect that the height is inferred (so that the aspect ratio is preserved) if I only pass one value. However, as far as I can judge from playing around with the command, this is not what is happening. If only one value is provided, it is taken for both the width and the height. If this is intended, I'd suggest to change the documentation to something like:

sharp resize <width> <height>
sharp resize <width_and_height>

Resize image to width × height respectively to a square if only one value is provided

A similar change would then also make sense for sharp --help, of course. This is just a suggestion to make this tool, which I really like so far, more user-friendly. 🙂

Proposal: Add `--animated` Global Option

Hi @vseventer,

First, thanks for this project. I find it very handy.

Second, I propose that we add a --animated Global Option. It’s an option given by sharp and it amounts to the same as --pages -1, but it’s a bit more descriptive.

I found some references to such a flag in the codebase, but couldn’t get it work. I tried putting --animated in many places on the command and the only one that didn’t complain about an unknown parameter was sharp-cli -i animated.gif animated -o animated.webp, but even then the output file wasn’t animated.

Thanks in advance.

`{dir}` is incorrect when using with url-template -o parameter

Hello!

Thanks for this tool, it works beautifully and is probably the best in town :-)

I discovered url-template but the {dir} directive does not correspond to what I expected. Ref to require('path').parse.

For example, this is a command I used and did not work as expected:

$ sharp -i content/playstation/images/boite-de-console-playstation-europeen.jpg -o '{dir}/{name}.sq{ext}' resize 170 170

vips__file_open_write: unable to open file "/Users/oncletom/workspace/emunova/emunova.net/%2FUsers%2Foncletom%2Fworkspace%2Femunova%2Femunova.net%2Fcontent%2Fplaystation%2Fimages/boite-de-console-playstation-europeen.sq.jpg" for writing
unix error: No such file or directory

I was expecting {dir} to be equal to either content/playstation/images or /Users/oncletom/workspace/emunova/emunova.net/content/playstation/images.

{dir} looks like an encoded value of some sort, which is prefixed by $(pwd).

Am I using it wrong?

Thanks for your help :-)

Support same file for input and output

What

Support overwriting the input file.

Why

We've been historically able to do this, but I removed that feature since it led to errors when processing large files. The node dependency I relied upon back then is no longer maintained, so there might be a better alternative. This is also a user ask in #23.

How

  • sharp -i file.jpg -o file.jpg: input file is overwritten with the processed image.
  • sharp -i *.jpg -o ./: multiple input files are overwritten with processed images.

[bug] layout parameter not working?

When I run

sharp --input image.png --output image_pyramid tile 256 --layout google

I keep getting this error:

Unsupported output format dz

I also tried --layout zoomify but it doesn't work either. Any tips?

Does not Install on ARM64 M1 Apple Silicone

Hello, I just found this package and tried installing on my M1 MacBook Pro.

It failed because Sharp in version 0.25.4 does not have ARM64 support.

However, I have used Sharp in version 0.30.3 in other projects which does have ARM64 support.

Can we just update the dependency for this library and release a new version or is there more work needed?

"input buffer constains unsupported image format" when using recursive glob

whenever I try to run sharp cli on a folder with subfolders to optimize pngs

this throws: Input buffer contains unsupported image format

sharp --input './**/*.png' -o {dir} --optimize

but this works:

sharp --input './**/*.jpg' -o {dir} --optimize

often times when this fails, it will change all my images to blank corrupted files.

note
this appears to occur when there is a corrupt/empty file in the matching group of files, could there be something done to skip invalid files so it doesn't destroy all my images?

environment info:
OS: windows 10
sharp 1.13.1
node v12.16.1

Tests are failing because of missing libheif

I get 7 errors when i run npm test. They all seems related to libheif being missing. Is there any way I can fix this? I am trying to create a pull request where sharp is updated to the latest v0.24.0, because that solves expo/expo-cli#1373.

 Error: The heif operation requires libvips to have been installed with support for libheif
 AssertionError: ["webp"] must have length of 2
 AssertError: expected heif to be called with match 
 AssertionError: ["webp","tiff","jpeg"] must have length of 4
 AssertError: expected heif to be called with match 
 AssertionError: ["webp","tiff","jpeg"] must have length of 4
 AssertError: expected heif to be called with match 

Full error log

  1) sharp-cli <options> [command..]
       <options>
         --hcompression
           must execute the pipeline:
     Error: The heif operation requires libvips to have been installed with support for libheif
      at Sharp.heif (node_modules/sharp/lib/output.js:456:11)
      at Function.invoke (node_modules/sinon/lib/sinon/spy.js:302:51)
      at Sharp.heif (node_modules/sinon/lib/sinon/spy.js:90:30)
      at /Users/janaagaard/Projects/sharp-cli/lib/cli.js:83:305
      at /Users/janaagaard/Projects/sharp-cli/lib/queue.js:26:154
      at Array.reduce (<anonymous>)
      at Array.value (lib/queue.js:26:84)
      at Context.<anonymous> (test/cli.js:263:32)
      at /Users/janaagaard/Projects/sharp-cli/lib/cli.js:91:31
      at parse (node_modules/yargs/yargs.js:567:18)
      at Object.cli.parse (lib/cli.js:74:31)
      at Context.<anonymous> (test/cli.js:252:32)
      at processImmediate (internal/timers.js:456:21)

  2) sharp-cli <options> [command..]
       <options>
         --lossless
           must update the pipeline:
     AssertionError: ["webp"] must have length of 2
      at Context.<anonymous> (test/cli.js:320:40)
      at /Users/janaagaard/Projects/sharp-cli/lib/cli.js:91:31
      at parse (node_modules/yargs/yargs.js:567:18)
      at Object.cli.parse (lib/cli.js:74:31)
      at Context.<anonymous> (test/cli.js:313:32)
      at processImmediate (internal/timers.js:456:21)

  3) sharp-cli <options> [command..]
       <options>
         --lossless
           must execute the pipeline:
     AssertError: expected heif to be called with match 
      at Object.fail (node_modules/sinon/lib/sinon/assert.js:106:21)
      at failAssertion (node_modules/sinon/lib/sinon/assert.js:65:16)
      at Object.assert.<computed> [as calledWithMatch] (node_modules/sinon/lib/sinon/assert.js:91:13)
      at Context.<anonymous> (test/cli.js:326:22)
      at /Users/janaagaard/Projects/sharp-cli/lib/cli.js:91:31
      at parse (node_modules/yargs/yargs.js:567:18)
      at Object.cli.parse (lib/cli.js:74:31)
      at Context.<anonymous> (test/cli.js:313:32)
      at processImmediate (internal/timers.js:456:21)

  4) sharp-cli <options> [command..]
       <options>
         --q
           must update the pipeline:
     AssertionError: ["webp","tiff","jpeg"] must have length of 4
      at Context.<anonymous> (test/cli.js:538:42)
      at /Users/janaagaard/Projects/sharp-cli/lib/cli.js:91:31
      at parse (node_modules/yargs/yargs.js:567:18)
      at Object.cli.parse (lib/cli.js:74:31)
      at Context.<anonymous> (test/cli.js:531:34)
      at processImmediate (internal/timers.js:456:21)

  5) sharp-cli <options> [command..]
       <options>
         --q
           must execute the pipeline:
     AssertError: expected heif to be called with match 
      at Object.fail (node_modules/sinon/lib/sinon/assert.js:106:21)
      at failAssertion (node_modules/sinon/lib/sinon/assert.js:65:16)
      at Object.assert.<computed> [as calledWithMatch] (node_modules/sinon/lib/sinon/assert.js:91:13)
      at Context.<anonymous> (test/cli.js:546:24)
      at /Users/janaagaard/Projects/sharp-cli/lib/cli.js:91:31
      at parse (node_modules/yargs/yargs.js:567:18)
      at Object.cli.parse (lib/cli.js:74:31)
      at Context.<anonymous> (test/cli.js:531:34)
      at processImmediate (internal/timers.js:456:21)

  6) sharp-cli <options> [command..]
       <options>
         --quality
           must update the pipeline:
     AssertionError: ["webp","tiff","jpeg"] must have length of 4
      at Context.<anonymous> (test/cli.js:538:42)
      at /Users/janaagaard/Projects/sharp-cli/lib/cli.js:91:31
      at parse (node_modules/yargs/yargs.js:567:18)
      at Object.cli.parse (lib/cli.js:74:31)
      at Context.<anonymous> (test/cli.js:531:34)
      at processImmediate (internal/timers.js:456:21)

  7) sharp-cli <options> [command..]
       <options>
         --quality
           must execute the pipeline:
     AssertError: expected heif to be called with match 
      at Object.fail (node_modules/sinon/lib/sinon/assert.js:106:21)
      at failAssertion (node_modules/sinon/lib/sinon/assert.js:65:16)
      at Object.assert.<computed> [as calledWithMatch] (node_modules/sinon/lib/sinon/assert.js:91:13)
      at Context.<anonymous> (test/cli.js:546:24)
      at /Users/janaagaard/Projects/sharp-cli/lib/cli.js:91:31
      at parse (node_modules/yargs/yargs.js:567:18)
      at Object.cli.parse (lib/cli.js:74:31)
      at Context.<anonymous> (test/cli.js:531:34)
      at processImmediate (internal/timers.js:456:21)

Support a directory as output

What

Support a directory as output (-o dir/).

Why

There have been multiple reports (#8, #13) where it is assumed the input files are saved in the output directory. The readme even shows this as an example (sharp -i ./input.jpg -o ./out resize 300 200 - out/input.jpg will be a [...] version of input.jpg).

It makes sense for the CLI to support this ask.

How

The following behavior is only true if the output directory exists. Otherwise, current behavior applies.

  • sharp -i single-file.jpg -o dir/: single output file is dir/single-file.jpg.
  • sharp -i *.jpg -o dir/: multiple output files are dir/*.jpg
  • sharp -i single-file-*.jpg -o dir/: single output file is dir/single-file-*.jpg.

Help converting a imagemagick command to sharp-cli

Hi!

First of all sorry for bothering you with this question.

I'm in a process to switch from imagemagick to sharp-cli but i'm having headaches trying to "convert" this composite command (who basically "stamps" a emoji .png file into a Windows Folder icon .png and outputs the composite result in another .png file for further processing):

magick <windows_folder_icon_dir>\256.png emoji_256.png -gravity SouthEast -geometry +16+29 -composite "compositeicon_256.png"

Is possible to make the same result using sharp-cli alone? Thanks in advance!

No exit code 1 thrown when command fails to run

Error

When unknown arguments are attached to the resize command the output of the cli gives the error shown below.

Unknown argument: min

Specify --help for available options

Usage

The command below was used when throwing the error.

sharp -i image.jpg -o image.jpg resize 360 640 -q 100 --lossless --min

Expected Response

I expected that the cli would throw an exit code of 1 when the command fails.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.