Coder Social home page Coder Social logo

imagemin's Introduction

imagemin

Minify images seamlessly





Install

$ npm install imagemin

Usage

import imagemin from 'imagemin';
import imageminJpegtran from 'imagemin-jpegtran';
import imageminPngquant from 'imagemin-pngquant';

const files = await imagemin(['images/*.{jpg,png}'], {
	destination: 'build/images',
	plugins: [
		imageminJpegtran(),
		imageminPngquant({
			quality: [0.6, 0.8]
		})
	]
});

console.log(files);
//=> [{data: <Buffer 89 50 4e …>, destinationPath: 'build/images/foo.jpg'}, …]

API

imagemin(input, options?)

Returns Promise<object[]> in the format {data: Buffer, sourcePath: string, destinationPath: string}.

input

Type: string[]

File paths or glob patterns.

options

Type: object

destination

Type: string

Set the destination folder to where your files will be written. If no destination is specified, no files will be written.

plugins

Type: Array

Plugins to use.

glob

Type: boolean
Default: true

Enable globbing when matching file paths.

imagemin.buffer(buffer, options?)

Returns Promise<Buffer>.

buffer

Type: Buffer

Buffer to optimize.

options

Type: object

plugins

Type: Array

Plugins to use.

Related

imagemin's People

Contributors

1000ch avatar ahmednuaman avatar antongolub avatar bevacqua avatar eklingen avatar jorrit avatar karlbecker avatar kevva avatar kswedberg avatar malash avatar ntwb avatar realityking avatar shinnn avatar sindresorhus avatar slavanga avatar stevenvachon avatar tprobinson avatar transitive-bullshit avatar tylerball avatar vitalykrenel 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  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

imagemin's Issues

How to use svgo with no buffer or file?

I fs.readFile'ed a JPEG and ran its Buffer through Imagemin.jpegtran() and it returned the modified Buffer.

I then converted that to a base64 string and put it in an SVG <image>.

Now that I'd like to run Imagemin.svgo() on my string, I'm not sure how and there doesn't appear to be a non-deprecated way to convert a string to a binary Buffer.

Are there any options I've missed? I'd rather not have to include svgo as an additional dependency.

WebP plugin

been searching and couldn't find any for the WebP format.

Any clues where I can find one?

Write to file for OptiPNG

Since OptiPNG doesn't support reading from stdin we need to write a file that can be read by OptiPNG and then piped to stdout.

@sindresorhus, please fix this ;E;E.

No method "src"?

Really strange error from both version 0.3.0 and 0.2.3 using a pretty simple script. I'm guessing the error is from something else but this is just a bad catch by node, but worth sharing I suppose

➜  project git:(master) ✗ node imagemin.js
Found 214 images...

/usr/local/var/www/project/imagemin.js:28
  .src(src)
   ^
TypeError: Object #<Transform> has no method 'src'
    at /usr/local/var/www/project/imagemin.js:28:4
    at ChildProcess.exithandler (child_process.js:635:7)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:735:16)
    at Socket.<anonymous> (child_process.js:948:11)
    at Socket.EventEmitter.emit (events.js:95:17)
    at Pipe.close (net.js:466:12)

Running very simple script

var path = require('path');
var execFile = require('child_process').execFile;
var Imagemin = require('image-min');
var jpegtran = require('image-min').jpegtran;
var optipng = require('image-min').optipng;

var src = [],
    imagemin = new Imagemin(),
    fileTypes = ['jpg', 'png', 'gif'];

execFile('find', [path.join(process.cwd(), 'production')], function(err, stdout, stderr) {

  var tmp = stdout.split('\n'),
      i = 0;

  // Only image files (png, jpg, gif)
  tmp.forEach(function(item, index){
    for(i = 0; i < fileTypes.length; i++){
      if(item.indexOf('.' + fileTypes[i]) !== -1){
        src.push(item);
      }
    }
  });

  console.log("Found " + src.length + " images...");

  imagemin
  .src(src)
  .dest('dist')
  .use(jpegtran({ progressive: true }))
  .use(optipng({ optimizationLevel: 4 }))
  .optimize(function (err, files) {
      console.log(files);
  });

});

The output from the REPL is also strange:

> new Imagemin()
{ _readableState: 
   { highWaterMark: 16384,
     buffer: [],
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: false,
     ended: false,
     endEmitted: false,
     reading: false,
     calledRead: false,
     sync: false,
     needReadable: true,
     emittedReadable: false,
     readableListening: false,
     objectMode: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: 
   { end: { [Function: g] listener: [Function: onend] },
     finish: { [Function: g] listener: [Function] } },
  _maxListeners: 10,
  _writableState: 
   { highWaterMark: 16384,
     objectMode: false,
     needDrain: false,
     ending: false,
     ended: false,
     finished: false,
     decodeStrings: true,
     defaultEncoding: 'utf8',
     length: 0,
     writing: false,
     sync: true,
     bufferProcessing: false,
     onwrite: [Function],
     writecb: null,
     writelen: 0,
     buffer: [],
     errorEmitted: false },
  writable: true,
  allowHalfOpen: true,
  _transformState: 
   { afterTransform: [Function],
     needTransform: false,
     transforming: false,
     writecb: null,
     writechunk: null },
  _transform: [Function: noop] }
> new Imagemin().src
undefined

like the function doesn't exist

Streaming interface

Would be very useful if imagemin handled streams. A module handling IO is really an anti-pattern and makes it difficult to use with eg. gulp: https://github.com/sindresorhus/gulp-imagemin

Should probably be in the individual modules, but lets discuss here.

Example of how it could be done:
https://github.com/papandreou/node-jpegtran
https://github.com/papandreou/node-optipng

Basically, save it in a temp location. You kinda already do that with the cache thing. Or just stdin/stdout for the ones that supports that.

Favicon support?

Just wondering ... since there is no imagemin for favicons, favicon support might be out of question.

Fatal error: Maximum call stack size exceeded

Minification throws up on JPEG with:

(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
...
Fatal error: Maximum call stack size exceeded
...
(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.

node.js:0
// Copyright Joyent, Inc. and other Node contributors.
^
RangeError: Maximum call stack size exceeded

Running it in conjunction of grunt-contrib-imagemin 0.6.0-pre.

Platform:

Mac OS X 10.8.5
Xcode 5.0
node: v0.10.21

Cc @sindresorhus.

Images do not seem to be compressing and saving in place

I need to run several hundred folders of images through gulp-imagemin for compressing .jpg files. I'm wanting to just save over the existing files rather than moving them to another destination. Here is my gulp file..

var gulp = require('gulp');
var imagemin = require('gulp-imagemin');

gulp.task('default', function () {
    return gulp.src('images/products/dirs/**/*.jpg')
        .pipe(imagemin())
        .pipe(gulp.dest('images/products/dirs/**/*.jpg'));
});

It runs fine in the command line, but when (I assume) it gets to the end of the images to compress it hangs. Also when I check the image sizes, they haven't changed. Any suggestions?

debug-imagemin

spawn ENOENT Windows7 64bit

I've got simple gulp task:

return gulp.src('./builds/build/static/img/*.png')
    .pipe(imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [pngcrush()]
    }))

It works on Mac, but doesn't work on Windows 7 64bit.

Error: spawn ENOENT.

Could you help me with that problem?

Command failed

I am getting this weird error on my Mac:

[14:59:33] Starting 'imagemin'...
{ [Error: Command failed: ]
  plugin: 'gulp-imagemin:',
  showStack: false,
  name: 'Error',
  message: 'Command failed: ',
  stack: 'Error: Command failed: \n    at ChildProcess.exithandler (child_process.js:647:15)\n    at ChildProcess.emit (events.js:98:17)\n    at maybeClose (child_process.js:755:16)\n    at Socket.<anonymous> (child_process.js:968:11)\n    at Socket.emit (events.js:95:17)\n    at Pipe.close (net.js:465:12)' }

the gulp code is:

gulp.task('imagemin', ['clean:img'], function() {
    return gulp.src(paths.uncompressedImages)
        .pipe(imagemin({
            optimizationLevel: 4,
            progressive:       true,
            interlaced:        true
        }))
        .on('error', console.error)
        .pipe(gulp.dest(paths.img))
})

Getting numerous errors on `npm install --save-dev imagemin`

I'm behind a corporate proxy and have set it up and set strict-ssl to false and the ca to "" but it still doesn't seem to be working. I don't have any issues installing other packages atm.

Errors:

> [email protected] postinstall C:\web\www\gxl-build\node_modules\gulp-imagemin\node_modules\imagemin\node_modules\imagemin-gifs
icle\node_modules\gifsicle
> node index.js

\
? Installation of gifsicle failed

Try installing the binary manually by visiting http://www.lcdf.org/gifsicle/
and choose the desired binary for your platform.

Then try reinstalling this module again.
|


> [email protected] postinstall C:\web\www\gxl-build\node_modules\gulp-imagemin\node_modules\imagemin\node_modules\imagemin-
pngquant\node_modules\pngquant-bin
> node index.js

? pre-build test failed, compiling from source...
libpng-dev is installed

[Error: CERT_UNTRUSTED]
\


> [email protected] postinstall C:\web\www\gxl-build\node_modules\gulp-imagemin\node_modules\imagemin\node_modules\imagemin-o
ptipng\node_modules\optipng-bin
> node index.js

? pre-build test failed, compiling from source...
? Error: Command failed: '.' is not recognized as an internal or external command,
operable program or batch file.




> [email protected] postinstall C:\web\www\gxl-build\node_modules\gulp-imagemin\node_modules\imagemin\node_modules\imagemin-
jpegtran\node_modules\jpegtran-bin
> node index.js

? CERT_UNTRUSTED
? CERT_UNTRUSTED
[email protected] node_modules\gulp-imagemin
├── [email protected]
├── [email protected]
├── [email protected] ([email protected], [email protected], [email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], multi
[email protected], [email protected])
└── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected],
 [email protected], [email protected], [email protected], [email protected], [email protected], imagemin-jpeg
[email protected])

cli.js help info doesn't seem right

Looks like you need to update the description on the -i -o and -p options in the help() function on the cli.js script. Just letting you know. :)

Error: Cannot find module 'imagemin-optipng'

Tried reinstall but still get this error

› imagemin

module.js:340
    throw err;
    ^
Error: Cannot find module 'imagemin-optipng'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/tcarlsen/.nvm/v0.10.26/lib/node_modules/imagemin/index.js:171:26)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

On install this error is showing:

npm WARN optional dep failed, continuing [email protected]

> [email protected] postinstall /Users/tcarlsen/.nvm/v0.10.26/lib/node_modules/imagemin/node_modules/imagemin-pngquant/node_modules/pngquant-bin
> node index.js

✗ pre-build test failed, compiling from source...
✗ Error: Command failed: In file included from pngquant.c:59:
./rwpng.h:35:10: fatal error: 'png.h' file not found
#include "png.h"    /* libpng header; includes zlib.h */
         ^
1 error generated.
make: *** [pngquant.o] Error 1

Pipe vinyl files to plugins

Use vinyl for buffers. Maybe makes sense to use vinyl-fs for files which would add support for globs etc. Or maybe just fs.readFile files and create a vinyl file from the buffer to keep things simple (i.e not using vinyl-fs but only vinyl).

wdyt, @sindresorhus?

EMFILE error while using async.eachSeries() on Linux Mint

Here's my code:

var fs = require('fs');
var async = require('async');
var imagemin = require('image-min');
var path = require('path');

fs.readdir('./catalog/',function (err, files) {
  async.eachSeries(files, function (file, callback) {
    var src = fs.createReadStream('catalog/' + file);
    var ext = path.extname(src.path);

    src
      .pipe(imagemin({ ext: ext }))
      .pipe(fs.createWriteStream('output/' + file));
    callback()
  }, function (err) {
      console.log(err);
  });
});

And here's the error:

child_process.js:927
    throw errnoException(process._errno, 'spawn');
          ^
Error: spawn EMFILE
    at errnoException (child_process.js:980:11)
    at ChildProcess.spawn (child_process.js:927:11)
    at exports.spawn (child_process.js:715:9)
    at spawn (/media/igor/Podaci/Slike/node_modules/image-min/node_modules/win-spawn/index.js:54:10)
    at Imagemin._optimizeJpeg (/media/igor/Podaci/Slike/node_modules/image-min/index.js:86:12)
    at Imagemin.optimize (/media/igor/Podaci/Slike/node_modules/image-min/index.js:29:19)
    at module.exports (/media/igor/Podaci/Slike/node_modules/image-min/index.js:123:21)
    at /media/igor/Podaci/Slike/app.js:12:13
    at iterate (/media/igor/Podaci/Slike/node_modules/async/lib/async.js:142:13)
    at /media/igor/Podaci/Slike/node_modules/async/lib/async.js:153:25
    at /media/igor/Podaci/Slike/app.js:14:5

eachLimit() produces the same error, regardless of the limit.
The catalog folder contains about 10k pics.

bin deps as optionalDependencies

Should prevent them from failing image-min to install. Thoughts?

If you don't already do it, you should fallback to checking path, and then pass through with a warning or something.

pngquant?

Why isn't pngquant included?

It's in the example in the readme.

Callback error

The callback should return any error in the first argument, per Node standards.

Cannot install from npm shrinkwrap

Repo to reproduce: https://github.com/vladikoff/imagemin-wrap

npm WARN package.json [email protected] No description
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] No repository field.
-
> [email protected] postinstall /Users/vfilippov/tmp/imagemin-wrap/node_modules/grunt-contrib-imagemin/node_modules/imagemin/node_modules/imagemin-gifsicle/node_modules/gifsicle
> node index.js


> [email protected] postinstall /Users/vfilippov/tmp/imagemin-wrap/node_modules/grunt-contrib-imagemin/node_modules/imagemin/node_modules/imagemin-jpegtran/node_modules/jpegtran-bin
> node index.js

-
> [email protected] postinstall /Users/vfilippov/tmp/imagemin-wrap/node_modules/grunt-contrib-imagemin/node_modules/imagemin/node_modules/imagemin-optipng/node_modules/optipng-bin
> node index.js

✔︎ pre-build test passed successfully!
npm ERR! cb() never called!
npm ERR! not ok code 0
~/tmp/imagemin-wrap on master*
$ 

Modules not found when using grunt

When using grunt with imagemin as one of the tasks I get this error:

Loading "imagemin.js" tasks...ERROR
>> Error: Cannot find module 'imagemin-gifsicle'
Warning: Task "imagemin" not found. Use --force to continue.
Aborted due to warnings.

If I add imagemin-gifsicle to package.json I get a similar error for imagemin-jpegtran, then imagemin-optipng and imagemin-pngquant.

Could it be the version specified in the package.json is too old?
https://github.com/webcompat/webcompat.com/blob/master/package.json

I'm using:

  • Ubuntu 14.04 (64-bit)
  • Node 0.10.30
  • npm 1.4.23
  • imagemin 0.4.9
  • grunt-contrib-imagemin: 0.7.2

npm WARN optional dep failed, continuing [email protected]

npm install --save image-min

path.js:360
        throw new TypeError('Arguments to path.join must be strings');
              ^
TypeError: Arguments to path.join must be strings
    at path.js:360:15
    at Array.filter (native)
    at Object.exports.join (path.js:358:36)
    at Object.<anonymous> (/Users/dwick/work/code/node_modules/image-min/node_modules/imagemin-optipng/node_modules/optipng-bin/index.js:14:24)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)

This breaks grunt-contrib-imagemin and currently I'm unable to install a working version of it.

Consider using pngout

Not important, but might be a nice addition.

There's a distribution issue though:

Redistributing, repackaging, or reusing the PNGOUT or KZIP executable is prohibited without the express consent of Ardfry Imaging, LLC, and a formal business agreement.

http://advsys.net/ken/utils.htm

I know ImageOptim was allowed though, so we might, but it's a hurdle.

Please update on npm

The npm version still uses the old non-streaming API, an update there to the latest version would be great.

Cannot find module 'imagemin-pngcrush'

I have installed libpng-dev but still have this error

module.js:340
throw err;
^
Error: Cannot find module 'imagemin-pngcrush'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (C:\Users\Samiullah\Desktop\Workflows\gulpfile.js:14:13)

at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Liftoff.handleArguments (C:\Users\Samiullah\AppData\Roaming\npm\node_module
s\gulp\bin\gulp.js:108:3)
at Liftoff.launch (C:\Users\Samiullah\AppData\Roaming\npm\node_modules\gulp\no
de_modules\liftoff\index.js:140:6)
at Object. (C:\Users\Samiullah\AppData\Roaming\npm\node_modules\gul
p\bin\gulp.js:59:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

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.