Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
High performance Node.js module to resize JPEG, PNG and WebP images using the libvips library
The sharp npm package is a high-performance Node.js module for resizing, converting, and manipulating images. It is built around the libvips image processing library, which allows it to handle large images and perform operations quickly and with a low memory footprint.
Image Resizing
Resizes an image to the specified width and height.
sharp('input.jpg').resize(300, 200).toFile('output.jpg', (err, info) => {});
Format Conversion
Converts an image from one format to another, such as JPEG to PNG.
sharp('input.jpg').toFormat('png').toBuffer().then(data => {});
Image Rotation
Rotates an image by a specified degree.
sharp('input.jpg').rotate(90).toBuffer().then(data => {});
Extracting Image Regions
Extracts a region of the image starting at the left and top offsets and with the specified width and height.
sharp('input.jpg').extract({ left: 100, top: 100, width: 300, height: 200 }).toFile('output.jpg', (err, info) => {});
Image Overlay
Overlays an image on top of another using composition.
sharp('input.jpg').composite([{ input: 'overlay.png', gravity: 'southeast' }]).toFile('output.jpg', (err, info) => {});
Adjusting Image Quality
Adjusts the quality of an image, useful for optimizing the file size.
sharp('input.jpg').jpeg({ quality: 80 }).toBuffer().then(data => {});
ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats. It is more comprehensive than sharp but can be slower and more memory-intensive.
An image processing library for Node written entirely in JavaScript, with zero native dependencies. Jimp is more accessible due to its pure JavaScript nature but generally performs slower than sharp.
GraphicsMagick for node.js, which is an image processing library that is a fork of ImageMagick. It is similar to ImageMagick in functionality and also provides a comprehensive set of image manipulation features but may not be as fast as sharp.
The typical use case for this high speed Node.js module is to convert large images of many formats to smaller, web-friendly JPEG, PNG and WebP images of varying dimensions.
The performance of JPEG resizing is typically 8x faster than ImageMagick and GraphicsMagick, based mainly on the number of CPU cores available. Everything remains non-blocking thanks to libuv and Promises/A+ are supported.
This module supports reading and writing images of JPEG, PNG and WebP to and from both Buffer objects and the filesystem. It also supports reading images of many other types from the filesystem via libmagick++ or libgraphicsmagick++ if present.
When generating JPEG output all metadata is removed and Huffman tables optimised without having to use separate command line tools like jpegoptim and jpegtran.
Anyone who has used the Node.js bindings for GraphicsMagick will find the API similarly fluent.
This module is powered by the blazingly fast libvips image processing library, originally created in 1989 at Birkbeck College and currently maintained by John Cupitt.
npm install sharp
libvips can take advantage of liborc if present. Warning: versions of liborc prior to 0.4.19 suffer memory leaks and version 0.4.19 suffers buffer overflows.
brew install homebrew/science/vips --with-webp --with-graphicsmagick
The gettext dependency of libvips can lead to a library not found for -lintl
error. If so, please try:
brew link gettext --force
sudo apt-get install libvips-dev
Compiling from source is recommended:
sudo apt-get install automake build-essential git gobject-introspection gtk-doc-tools libfftw3-dev libglib2.0-dev libjpeg-turbo8-dev libpng12-dev libwebp-dev libtiff5-dev libexif-dev libxml2-dev swig
git clone https://github.com/jcupitt/libvips.git
cd libvips
git checkout 7.38
./bootstrap.sh
./configure --enable-debug=no --enable-cxx=no --without-python --without-orc
make
sudo make install
sudo ldconfig
Requires libtiff4-dev
instead of libtiff5-dev
and has a bug in the libwebp package. Work around these problems by running these commands first:
sudo add-apt-repository ppa:lyrasis/precise-backports
sudo apt-get update
sudo apt-get install libtiff4-dev
Then follow Ubuntu 13.x instructions.
var sharp = require('sharp');
sharp('input.jpg').resize(300, 200).toFile('output.jpg', function(err) {
if (err) {
throw err;
}
// output.jpg is a 300 pixels wide and 200 pixels high image
// containing a scaled and cropped version of input.jpg
});
sharp('input.jpg').rotate().resize(null, 200).progressive().toBuffer(function(err, outputBuffer) {
if (err) {
throw err;
}
// outputBuffer contains 200px high progressive JPEG image data, auto-rotated using EXIF Orientation tag
});
sharp('input.png').rotate(180).resize(300).sharpen().quality(90).webp().then(function(outputBuffer) {
// outputBuffer contains 300px wide, upside down, sharpened, 90% quality WebP image data
});
sharp(inputBuffer).resize(200, 300).embedWhite().toFile('output.tiff').then(function() {
// output.tiff is a 200 pixels wide and 300 pixels high image containing a scaled
// version, embedded on a white canvas, of the image data in buffer
});
sharp('input.gif').resize(200, 300).embedBlack().webp(function(err, outputBuffer) {
if (err) {
throw err;
}
// outputBuffer contains WebP image data of a 200 pixels wide and 300 pixels high
// containing a scaled version, embedded on a black canvas, of input.gif
});
sharp(inputBuffer).resize(200, 200).max().jpeg().then(function(outputBuffer) {
// outputBuffer contains JPEG image data no wider than 200 pixels and no higher
// than 200 pixels regardless of the inputBuffer image dimensions
});
Constructor to which further methods are chained. input
can be one of:
Scale output to width
x height
. By default, the resized image is cropped to the exact size specified.
width
is the Number of pixels wide the resultant image should be. Use null
or undefined
to auto-scale the width to match the height.
height
is the Number of pixels high the resultant image should be. Use null
or undefined
to auto-scale the height to match the width.
Crop the resized image to the exact size specified, the default behaviour.
Preserving aspect ratio, resize the image to the maximum width or height specified.
Both width
and height
must be provided via resize
otherwise the behaviour will default to crop
.
Embed the resized image on a white background of the exact size specified.
Embed the resized image on a black background of the exact size specified.
Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation
tag. Mirroring is not supported.
angle
, if present, is a Number with a value of 0
, 90
, 180
or 270
.
Use this method without angle
to determine the angle from EXIF data.
Do not enlarge the output image if the input image width or height are already less than the required dimensions.
This is equivalent to GraphicsMagick's >
geometry option: "change the dimensions of the image only if its width or height exceeds the geometry specification".
Perform a mild sharpen of the resultant image. This typically reduces performance by 30%.
Use progressive (interlace) scan for JPEG and PNG output. This typically reduces compression performance by 30% but results in an image that can be rendered sooner when decompressed.
The output quality to use for lossy JPEG, WebP and TIFF output formats. The default quality is 80
.
quality
is a Number between 1 and 100.
An advanced setting for the zlib compression level of the lossless PNG output format. The default level is 6
.
compressionLevel
is a Number between -1 and 9.
An advanced setting that switches the libvips access method to VIPS_ACCESS_SEQUENTIAL
. This will reduce memory usage and can improve performance on some systems.
filename
is a String containing the filename to write the image data to. The format is inferred from the extension, with JPEG, PNG, WebP and TIFF supported.
callback
, if present, is called with a single argument (err)
containing an error message, if any.
A Promises/A+ promise is returned when callback
is not provided.
Write image data to a Buffer, the format of which will match the input image. JPEG, PNG and WebP are supported.
callback
, if present, gets two arguments (err, buffer)
where err
is an error message, if any, and buffer
is the resultant image data.
A Promises/A+ promise is returned when callback
is not provided.
Write JPEG image data to a Buffer.
callback
, if present, gets two arguments (err, buffer)
where err
is an error message, if any, and buffer
is the resultant JPEG image data.
A Promises/A+ promise is returned when callback
is not provided.
Write PNG image data to a Buffer.
callback
, if present, gets two arguments (err, buffer)
where err
is an error message, if any, and buffer
is the resultant PNG image data.
A Promises/A+ promise is returned when callback
is not provided.
Write WebP image data to a Buffer.
callback
, if present, gets two arguments (err, buffer)
where err
is an error message, if any, and buffer
is the resultant WebP image data.
A Promises/A+ promise is returned when callback
is not provided.
If limit
is provided, set the (soft) limit of libvips working/cache memory to this value in MB. The default value is 100.
This method always returns cache statistics, useful for determining how much working memory is required for a particular task.
Warnings such as Application transferred too many scanlines are a good indicator you've set this value too low.
var stats = sharp.cache(); // { current: 98, high: 115, limit: 100 }
sharp.cache(200); // { current: 98, high: 115, limit: 200 }
sharp.cache(50); // { current: 49, high: 115, limit: 50 }
npm test
Running the tests requires both ImageMagick and GraphicsMagick plus one of either libmagick++-dev or libgraphicsmagick++.
brew install imagemagick
brew install graphicsmagick
sudo apt-get install imagemagick graphicsmagick libmagick++-dev
Decompress a 2725x2225 JPEG image, resize and crop to 720x480, then compress to JPEG.
Module | Input | Output | Ops/sec | Speed-up |
---|---|---|---|---|
imagemagick-native | buffer | buffer | 0.97 | 1 |
imagemagick | file | file | 2.49 | 2.6 |
gm | buffer | file | 3.72 | 3.8 |
gm | buffer | buffer | 3.80 | 3.9 |
gm | file | file | 3.67 | 3.8 |
gm | file | buffer | 3.67 | 3.8 |
sharp | buffer | file | 13.62 | 14.0 |
sharp | buffer | buffer | 12.43 | 12.8 |
sharp | file | file | 13.02 | 13.4 |
sharp | file | buffer | 11.15 | 11.5 |
sharp +sharpen | file | buffer | 10.26 | 10.6 |
sharp +progressive | file | buffer | 9.44 | 9.7 |
sharp +sequentialRead | file | buffer | 11.94 | 12.3 |
You can expect much greater performance with caching enabled (default) and using 16+ core machines.
Copyright 2013, 2014 Lovell Fuller and Pierre Inglebert
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
FAQs
High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images
We found that sharp demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.