gm vs canvas vs image-size vs jimp vs sharp
图像处理库
gmcanvasimage-sizejimpsharp类似的npm包:

图像处理库

图像处理库是用于在Node.js环境中处理和操作图像的工具。这些库提供了多种功能,包括图像的创建、编辑、转换、压缩和尺寸调整等。选择合适的图像处理库可以显著提高开发效率和图像处理的性能。不同的库在功能、性能和易用性上各有特点,适合不同的应用场景。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
gm647,7356,979121 kB3681 年前MIT
canvas010,650469 kB4582 个月前MIT
image-size02,215378 kB491 年前MIT
jimp0-4.03 MB-1 年前MIT
sharp031,949534 kB1204 个月前Apache-2.0

功能对比: gm vs canvas vs image-size vs jimp vs sharp

性能

  • gm:

    GraphicsMagick库在处理大量图像时表现良好,但相较于其他库,性能可能稍逊,尤其是在处理复杂图像时。

  • canvas:

    Canvas库提供了一个强大的2D绘图API,能够高效地处理图形和图像生成,适合需要高性能图形操作的应用。

  • image-size:

    image-size库非常轻量,性能极佳,能够快速返回图像的尺寸信息,适合需要快速获取元数据的场景。

  • jimp:

    Jimp库的性能适中,适合简单的图像处理任务,但在处理大图像时可能不如其他库高效。

  • sharp:

    Sharp库以其卓越的性能而闻名,能够快速处理和转换大图像,特别适合需要高效图像处理的应用。

功能

  • gm:

    gm库提供了丰富的图像处理功能,包括转换、裁剪、调整大小等,适合批量处理图像。

  • canvas:

    Canvas库支持复杂的图形绘制和图像生成,适合需要自定义图形和图像处理的应用。

  • image-size:

    image-size库的功能非常专一,主要用于获取图像的尺寸信息,功能简单而高效。

  • jimp:

    Jimp库支持基本的图像处理功能,如裁剪、调整大小、过滤等,适合简单的图像编辑需求。

  • sharp:

    Sharp库支持多种图像格式的转换、调整大小、裁剪和压缩等功能,适合需要多样化图像处理的应用。

易用性

  • gm:

    gm库的API设计简单易用,适合快速上手,尤其是对于需要批量处理的场景。

  • canvas:

    Canvas库的API相对复杂,适合有一定图形处理经验的开发者使用。

  • image-size:

    image-size库非常易于使用,几乎不需要配置,适合快速获取图像尺寸的需求。

  • jimp:

    Jimp库的API友好,适合初学者,提供了简单的图像处理接口。

  • sharp:

    Sharp库的API设计合理,虽然功能强大,但学习曲线相对较陡,适合有一定经验的开发者。

支持的格式

  • gm:

    gm库支持几乎所有常见的图像格式,适合需要广泛格式支持的场景。

  • canvas:

    Canvas库支持多种图像格式的读取和生成,适合需要处理多种格式的应用。

  • image-size:

    image-size库支持多种图像格式的尺寸获取,但不支持图像处理。

  • jimp:

    Jimp库支持常见的图像格式,如JPEG、PNG等,适合基本的图像处理需求。

  • sharp:

    Sharp库支持多种图像格式的高效处理,包括JPEG、PNG、WebP等,适合需要多格式处理的应用。

社区支持

  • gm:

    gm库的社区相对较小,但仍然提供了一定的支持和文档。

  • canvas:

    Canvas库有一个活跃的社区,提供了丰富的文档和示例,适合需要社区支持的开发者。

  • image-size:

    image-size库的社区较小,但文档清晰,适合简单需求的开发者。

  • jimp:

    Jimp库有一个活跃的社区,提供了丰富的文档和示例,适合初学者。

  • sharp:

    Sharp库有一个强大的社区支持,提供了详细的文档和活跃的开发者支持,适合需要高效解决问题的开发者。

如何选择: gm vs canvas vs image-size vs jimp vs sharp

  • gm:

    选择GraphicsMagick(gm)库如果你需要一个简单的接口来访问GraphicsMagick的强大功能,适合处理批量图像操作和转换。它适合需要快速处理大量图像的场景。

  • canvas:

    选择Canvas库如果你需要一个强大的2D绘图API,能够在Node.js中生成图像并进行复杂的图形操作。它适合需要自定义图形和图像生成的应用。

  • image-size:

    选择image-size库如果你只需要获取图像的尺寸信息,而不需要进行其他复杂的图像处理。这是一个轻量级的库,适合快速获取图像元数据。

  • jimp:

    选择Jimp库如果你需要一个纯JavaScript实现的图像处理库,适合简单的图像编辑和处理任务。它易于使用,适合初学者和小型项目。

  • sharp:

    选择Sharp库如果你需要高性能的图像处理,特别是在处理大图像时。它支持流式处理和多种图像格式,适合需要快速处理和转换图像的应用。

gm的README

gm Build Status NPM Version

GraphicsMagick and ImageMagick for node

Bug Reports

When reporting bugs please include the version of graphicsmagick/imagemagick you're using (gm -version/convert -version) as well as the version of this module and copies of any images you're having problems with.

Getting started

First download and install GraphicsMagick or ImageMagick. In Mac OS X, you can simply use Homebrew and do:

brew install imagemagick
brew install graphicsmagick

then either use npm:

npm install gm

or clone the repo:

git clone git://github.com/aheckmann/gm.git

Use ImageMagick instead of gm

Subclass gm to enable ImageMagick 7+

const fs = require('fs')
const gm = require('gm').subClass({ imageMagick: '7+' });

Or, to enable ImageMagick legacy mode (for ImageMagick version < 7)

const fs = require('fs')
const gm = require('gm').subClass({ imageMagick: true });

Specify the executable path

Optionally specify the path to the executable.

const fs = require('fs')
const gm = require('gm').subClass({
  appPath: String.raw`C:\Program Files\ImageMagick-7.1.0-Q16-HDRI\magick.exe`
});

Basic Usage

var fs = require('fs')
  , gm = require('gm');

// resize and remove EXIF profile data
gm('/path/to/my/img.jpg')
.resize(240, 240)
.noProfile()
.write('/path/to/resize.png', function (err) {
  if (!err) console.log('done');
});

// some files would not be resized appropriately
// http://stackoverflow.com/questions/5870466/imagemagick-incorrect-dimensions
// you have two options:
// use the '!' flag to ignore aspect ratio
gm('/path/to/my/img.jpg')
.resize(240, 240, '!')
.write('/path/to/resize.png', function (err) {
  if (!err) console.log('done');
});

// use the .resizeExact with only width and/or height arguments
gm('/path/to/my/img.jpg')
.resizeExact(240, 240)
.write('/path/to/resize.png', function (err) {
  if (!err) console.log('done');
});

// obtain the size of an image
gm('/path/to/my/img.jpg')
.size(function (err, size) {
  if (!err)
    console.log(size.width > size.height ? 'wider' : 'taller than you');
});

// output all available image properties
gm('/path/to/img.png')
.identify(function (err, data) {
  if (!err) console.log(data)
});

// pull out the first frame of an animated gif and save as png
gm('/path/to/animated.gif[0]')
.write('/path/to/firstframe.png', function (err) {
  if (err) console.log('aaw, shucks');
});

// auto-orient an image
gm('/path/to/img.jpg')
.autoOrient()
.write('/path/to/oriented.jpg', function (err) {
  if (err) ...
})

// crazytown
gm('/path/to/my/img.jpg')
.flip()
.magnify()
.rotate('green', 45)
.blur(7, 3)
.crop(300, 300, 150, 130)
.edge(3)
.write('/path/to/crazy.jpg', function (err) {
  if (!err) console.log('crazytown has arrived');
})

// annotate an image
gm('/path/to/my/img.jpg')
.stroke("#ffffff")
.drawCircle(10, 10, 20, 10)
.font("Helvetica.ttf", 12)
.drawText(30, 20, "GMagick!")
.write("/path/to/drawing.png", function (err) {
  if (!err) console.log('done');
});

// creating an image
gm(200, 400, "#ddff99f3")
.drawText(10, 50, "from scratch")
.write("/path/to/brandNewImg.jpg", function (err) {
  // ...
});

Streams

// passing a stream
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream, 'img.jpg')
.write('/path/to/reformat.png', function (err) {
  if (!err) console.log('done');
});


// passing a downloadable image by url

var request = require('request');
var url = "www.abc.com/pic.jpg"

gm(request(url))
.write('/path/to/reformat.png', function (err) {
  if (!err) console.log('done');
});


// can also stream output to a ReadableStream
// (can be piped to a local file or remote server)
gm('/path/to/my/img.jpg')
.resize('200', '200')
.stream(function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
  stdout.pipe(writeStream);
});

// without a callback, .stream() returns a stream
// this is just a convenience wrapper for above.
var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
gm('/path/to/my/img.jpg')
.resize('200', '200')
.stream()
.pipe(writeStream);

// pass a format or filename to stream() and
// gm will provide image data in that format
gm('/path/to/my/img.jpg')
.stream('png', function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/reformatted.png');
  stdout.pipe(writeStream);
});

// or without the callback
var writeStream = fs.createWriteStream('/path/to/my/reformatted.png');
gm('/path/to/my/img.jpg')
.stream('png')
.pipe(writeStream);

// combine the two for true streaming image processing
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream)
.resize('200', '200')
.stream(function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
  stdout.pipe(writeStream);
});

// GOTCHA:
// when working with input streams and any 'identify'
// operation (size, format, etc), you must pass "{bufferStream: true}" if
// you also need to convert (write() or stream()) the image afterwards
// NOTE: this buffers the readStream in memory!
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream)
.size({bufferStream: true}, function(err, size) {
  this.resize(size.width / 2, size.height / 2)
  this.write('/path/to/resized.jpg', function (err) {
    if (!err) console.log('done');
  });
});

Buffers

// A buffer can be passed instead of a filepath as well
var buf = require('fs').readFileSync('/path/to/image.jpg');

gm(buf, 'image.jpg')
.noise('laplacian')
.write('/path/to/out.jpg', function (err) {
  if (err) return handle(err);
  console.log('Created an image from a Buffer!');
});

/*
A buffer can also be returned instead of a stream
The first argument to toBuffer is optional, it specifies the image format
*/
gm('img.jpg')
.resize(100, 100)
.toBuffer('PNG',function (err, buffer) {
  if (err) return handle(err);
  console.log('done!');
})

Custom Arguments

If gm does not supply you with a method you need or does not work as you'd like, you can simply use gm().in() or gm().out() to set your own arguments.

  • gm().command() - Custom command such as identify or convert
  • gm().in() - Custom input arguments
  • gm().out() - Custom output arguments

The command will be formatted in the following order:

  1. command - ie convert
  2. in - the input arguments
  3. source - stdin or an image file
  4. out - the output arguments
  5. output - stdout or the image file to write to

For example, suppose you want the following command:

gm "convert" "label:Offline" "PNG:-"

However, using gm().label() may not work as intended for you:

gm()
.label('Offline')
.stream();

would yield:

gm "convert" "-label" "\"Offline\"" "PNG:-"

Instead, you can use gm().out():

gm()
.out('label:Offline')
.stream();

which correctly yields:

gm "convert" "label:Offline" "PNG:-"

Custom Identify Format String

When identifying an image, you may want to use a custom formatting string instead of using -verbose, which is quite slow. You can use your own formatting string when using gm().identify(format, callback). For example,

gm('img.png').format(function (err, format) {

})

// is equivalent to

gm('img.png').identify('%m', function (err, format) {

})

since %m is the format option for getting the image file format.

Platform differences

Please document and refer to any platform or ImageMagick/GraphicsMagick issues/differences here.

Examples:

Check out the examples directory to play around. Also take a look at the extending gm page to see how to customize gm to your own needs.

Constructor:

There are a few ways you can use the gm image constructor.

    1. gm(path) When you pass a string as the first argument it is interpreted as the path to an image you intend to manipulate.
    1. gm(stream || buffer, [filename]) You may also pass a ReadableStream or Buffer as the first argument, with an optional file name for format inference.
    1. gm(width, height, [color]) When you pass two integer arguments, gm will create a new image on the fly with the provided dimensions and an optional background color. And you can still chain just like you do with pre-existing images too. See here for an example.

The links below refer to an older version of gm but everything should still work, if anyone feels like updating them please make a PR

Methods

compare

Graphicsmagicks compare command is exposed through gm.compare(). This allows us to determine if two images can be considered "equal".

Currently gm.compare only accepts file paths.

gm.compare(path1, path2 [, options], callback)
gm.compare('/path/to/image1.jpg', '/path/to/another.png', function (err, isEqual, equality, raw, path1, path2) {
  if (err) return handle(err);

  // if the images were considered equal, `isEqual` will be true, otherwise, false.
  console.log('The images were equal: %s', isEqual);

  // to see the total equality returned by graphicsmagick we can inspect the `equality` argument.
  console.log('Actual equality: %d', equality);

  // inspect the raw output
  console.log(raw);

  // print file paths
  console.log(path1, path2);
})

You may wish to pass a custom tolerance threshold to increase or decrease the default level of 0.4.

gm.compare('/path/to/image1.jpg', '/path/to/another.png', 1.2, function (err, isEqual) {
  ...
})

To output a diff image, pass a configuration object to define the diff options and tolerance.

var options = {
  file: '/path/to/diff.png',
  highlightColor: 'yellow',
  tolerance: 0.02
}
gm.compare('/path/to/image1.jpg', '/path/to/another.png', options, function (err, isEqual, equality, raw) {
  ...
})

composite

GraphicsMagick supports compositing one image on top of another. This is exposed through gm.composite(). Its first argument is an image path with the changes to the base image, and an optional mask image.

Currently, gm.composite() only accepts file paths.

gm.composite(other [, mask])
gm('/path/to/image.jpg')
.composite('/path/to/second_image.jpg')
.geometry('+100+150')
.write('/path/to/composite.png', function(err) {
    if(!err) console.log("Written composite image.");
});

montage

GraphicsMagick supports montage for combining images side by side. This is exposed through gm.montage(). Its only argument is an image path with the changes to the base image.

Currently, gm.montage() only accepts file paths.

gm.montage(other)
gm('/path/to/image.jpg')
.montage('/path/to/second_image.jpg')
.geometry('+100+150')
.write('/path/to/montage.png', function(err) {
    if(!err) console.log("Written montage image.");
});

Contributors

https://github.com/aheckmann/gm/contributors

Inspiration

http://github.com/quiiver/magickal-node

Plugins

https://github.com/aheckmann/gm/wiki

Tests

npm test

To run a single test:

npm test -- alpha.js

License

(The MIT License)

Copyright (c) 2010 Aaron Heckmann

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.