Giter Site home page Giter Site logo

imagemin-jpeg-recompress'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: <Uint8Array 89 50 4e …>, destinationPath: 'build/images/foo.jpg'}, …]

API

imagemin(input, options?)

Returns Promise<object[]> in the format {data: Uint8Array, 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

The plugins to use.

glob

Type: boolean
Default: true

Enable globbing when matching file paths.

imagemin.buffer(data, options?)

Returns Promise<Uint8Array>.

data

Type: Uint8Array

The image data to optimize.

options

Type: object

plugins

Type: Array

Plugins to use.

Related

imagemin-jpeg-recompress's People

Contributors

1000ch avatar adityapatadia avatar kevva avatar leachim2k avatar shinnn avatar sindresorhus avatar timdp avatar webketje 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

imagemin-jpeg-recompress's Issues

Output file is larger than input, aborting!

Hello!
I use use gulp-image package with imagemin-jpeg-recompress plugin to optimize mutiple files:

gulp.task('images', config.img.description, wrapPipe(function (success, error) {
	return gulp
		.src(config.source, config.options)
		.pipe(imagemin([
			imageminJpegRecompress({ quality: 'low' })
		]).on('error', error))
		.pipe(gulp.dest(config.destination))
		.on('end', () => {
			notifier('Images have been minified.');
		}, success);
}));

If we get at least one non-optimizable file during processing, all output piping will be aborted:

[15:04:26] 'images' errored after 725 ms
[15:04:26] Error in plugin 'gulp-imagemin'
Message:
    Output file is larger than input, aborting!
Details:
    code: 1
    killed: false
    stdout: 
    stderr: Output file is larger than input, aborting!
    failed: true
    signal: null
    cmd: /raid/vhosts/files/node_modules/jpeg-recompress-bin/vendor/jpeg-recompress --quiet --quality low --strip /tmp/8bb35c3a-115a-4658-beb5-0be9b95e8141 /tmp/4e460681-5354-4941-891b-7dcfbb4babaf
    timedOut: false
    fileName: /full_file_name_is_here.jpg

How can I continue piping and just copy non-optimized file as-is to destination in this case?
Thank you.

`GLIBC_2.14' not found (Debian 7.6)

I get the following when trying to save with this plugin:

 /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.14' not found

The output of running libc.so.6:

GNU C Library (Debian EGLIBC 2.13-38+deb7u3) stable release version 2.13

Using the latest version of libc6 from apt-get. Is it the case that I can't use it with my version of Debian?

Use imagemin-jpeg-recompress in the grunt-contrib-imagemin workflow

I tried to configure this plugin in my grunt workflow but it's not working.

module.exports = function(grunt, options ) {
  'use strict';
  var jpegRecompress = require('imagemin-jpeg-recompress');
  return {
    options: {
      optimizationLevel: 3,
      use: [jpegRecompress({ loops: 3 })]
    },
    dev: {
      files:[
          {
            expand: true,
            cwd: 'src/',
            src:['**/*.{png,jpg,gif}'],
            dest: 'dest'
        }
      ]
    }
  };
};

but it raising an error

Fatal error: Object #<Object> has no method 'apply'

It looks like the imagemin is expecting a function but the plugin is returning an object ( probably a stream ?). Do the imagemin apis has changed lately ?
Unfortunately I haven't had time yet to go deep in the code/problem.
Any ideas? Thanks

CMYK support

Hi,

Great job with this plugin. Just wandering if there is support for CMYK jpgs. I get an error : Unsupported color conversion request

Cheers

Is there a way to provide an array of files with wildcards?

Right now it looks like I can only run this plugin on a per file basis, but I want it to do some pattern matching (like most plugins used with grunt).

Is that at all possible right now?

If not, can it be added?

I'm looking for a pattern like so:

files: [{
    expand: true,
    cwd: 'img/',
    src: ['*.jpg', 'projects/*.jpg'],
    dest: 'img/_build'
}]

Unable to process images, getting the error "Error: write EPIPE"

Error that I get

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: write EPIPE
    at exports._errnoException (util.js:746:11)
    at WriteWrap.afterWrite (net.js:775:14)

My code

return gulp.src('src/img/*.jpg')
        .pipe(imageminJpegRecompress({loops: 3})())
        .pipe(gulp.dest('dist/img'));

Let me know if you need any more info from me.

How are quality presets and min/max settings related?

It's unclear from the documentation how these options are related. If I choose the "high" quality preset, does that have any effect on the min/max compression options? E.g. if the high quality preset is used, does that mean that the min is set at 60 rather than the default (40)?

Photoshop intergration

Hi there,

Great software you have there. was wondering if possible to integrate it as a script in photoshop somehow to save work time?

Handle larger output file better

It took me a while to figure out why jpeg-recompress suddenly stopped generating output files. It turns out that, if the settings cause the output file to be larger than the input file (which can happen with default settings), jpeg-recompress prints an error and has an exit status of 1. However, imagemin-jpeg-recompress only throws an obscure "Command failed" in this case. It would be nice if you could detect it.

Premature end of JPEG file (Gulp)

I'm trying to recompress jpeg after saving via Photoshop (Save As)

var jpegRecompress = require('imagemin-jpeg-recompress');

gulp.task('jpg', function () {
    gulp.src('./images/temp/*.jpg')
        .pipe(jpegRecompress({loops: 3})())
        .pipe(gulp.dest('./images/'));
});

error:

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: Premature end of JPEG file
JPEG datastream contains no image

    at ChildProcess.<anonymous> (D:\projects\gulp-it\node_modules\imagemin-jpeg-recompress\index.js:100:8)
    at ChildProcess.emit (events.js:110:17)
    at maybeClose (child_process.js:1008:16)
    at Socket.<anonymous> (child_process.js:1176:11)
    at Socket.emit (events.js:107:17)
    at Pipe.close (net.js:476:12)

When I'm tring to recompress jpeg, saved via Save For Web in Photoshop:

error:

Error: Premature end of JPEG file
Bogus DQT index 9

Any suggestions?

imagemin-jpeg-recompress returns Error when compressing

´´´´
$ npm install imagemin-jpeg-recompress
npm WARN package.json [email protected] No repository field.
|

[email protected] postinstall C:\sites_testes\node_modules\imagemin-j
peg-recompress\node_modules\jpeg-recompress-bin
node lib/install.js

√ jpeg-recompress pre-build test passed successfully

[email protected] node_modules\imagemin-jpeg-recompress
├── [email protected]
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected], [email protected])

C:>grunt imagemin
Running "imagemin:main" (imagemin) task
Warning: Error: Premature end of JPEG file
Bogus Huffman table definition
in file _images/mee.jpg Use --force to continue.

Aborted due to warnings.
´´´´

my task config is this:

´´´´
var imageCompressEngine = require('imagemin-jpeg-recompress');

var globalConfig = {

imagemin: {
  main: {
    options: {
      optimizationLevel: 7,
      pngquant: true,
      progressive: true,
      use: [imageCompressEngine()]
    },
    files: [
      {
        expand: true,
        cwd: '<%= cfg.root %><%= cfg.src.images %>',
        src: ['**/*.{png,jpg,jpeg,gif,ico}'],
        dest: '<%= cfg.root %><%= cfg.dest.images %>'
      }
    ]
  }
},

});
´´´´
My dependences are the latest versions of
"grunt-contrib-imagemin": "^0.9.2", and "imagemin-jpeg-recompress": "^4.0.0".

I'm working on windows OS, if i use another plugin, like imagemin-mozjpeg, it works perfectly.
I want to use this plugin, because it as a better compression.

Best regards, Mário Silva

Error installing imagemin-jpeg-recompress on ubuntu arm64 vps

npm ERR! code 1
npm ERR! path /home/ubuntu/node2/node_modules/jpeg-recompress-bin
npm ERR! command failed
npm ERR! command sh -c node lib/install.js
npm ERR! Command failed: /home/ubuntu/node2/node_modules/jpeg-recompress-bin/vendor/jpeg-recompress --version
npm ERR! /home/ubuntu/node2/node_modules/jpeg-recompress-bin/vendor/jpeg-recompress: 2: Syntax error: word unexpected (expecting ")")
npm ERR!
npm ERR!
npm ERR! jpeg-recompress pre-build test failed

TypeError: pipe.then is not a function

const imagemin = require('imagemin');
const imageminJpegRecompress = require('imagemin-jpeg-recompress');

var path = process.argv[2];
var out = process.argv[3];

imagemin([path], out, {
    plugins: [
        imageminJpegRecompress()
    ]
}).then(files => {
    console.log(files);
    console.log("finished");
}).catch(err => {
    console.log("ERR:"+err);
    throw err;
});

I am getting this error when launching : node myscript.js .
I have seen this error already in similar plugins (imagemin/imagemin-webp#8), is it related?

not optimized = no output

When an image is already optimized or has, for example, 15Mpx dimensions and 0.5Mb filesize, jpeg-compress aborts.
So if I use gulp-imagemin, there's no output image, as exec-buffer throws an error for it.
It would be great, if you pass original image in such cases.

doesn't work on DigitalOcean dokku

work perfectly when i test it on localhost, but when i deploy to Digital Ocean compress dosesn't work.I am Using it with multer

      app.use( multer({ dest: './uploads/',
      limits: {

          fileSize : 10 * 1024 * 1024,
          fieldNameSize: 100,
          files: 5,
          fields: 8

      },

      onFileUploadComplete: function (file) {

          console.log( file.path+ ' upload complete');

          var imagemin = new Imagemin()
              .src(file.path)
              .dest(file.path)
              .use(jpegRecompress({
                  progressive: true,
                  loops: 7,
                  min: 30,
                  strip: true,
                  quality : 'low',
                  target : 0.7
              }));

          imagemin.optimize();
      },
      onFileUploadStart: function (file) {

      },
      onFileSizeLimit: function (file) {
          console.log('Failed: ToBiggZ')

      },
      onFilesLimit: function () {
          console.log('Crossed file limit!')
      },
      onError: function (error, next) {
          console.log(error)
          next(error)
      }
  }
));

Failed working with large numbers of JPGs

I tried to use jpeg-recompress on a directory consists of hundreds of thousands images. The directory size around 15 GB. I use Linux and Debian 9.
The command:

find /path/dir -type f -name '*.jpg' | xargs -P 50 -I {} jpeg-recompress --quality high --min 60 --method smallfry --strip {} {} ;

The command will result jpeg-recompress on HALT and shell session terminated after around 30 minutes.
Anyone can suggest me better line to work with huge directory?

spawn ... ENOENT

i hava create an image compress tool base on electron , use imagemin-jpeg-recompress to compress jpeg file , it is useful in electron develop mode,but there is an error when i build electron to a exe file ,

Error: Error in file: C:/Users/54657645/Desktop/images/1.jpg

spawn C:\Users\54657645\AppData\Local\Programs\imagecompress\resources\app.asar\node_modules\jpeg-recompress-bin\vendor\jpeg-recompress.exe ENOENT
    at exports._errnoException (util.js:1024)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:192)
    at onErrorNT (internal/child_process.js:374)
    at _combinedTickCallback (internal/process/next_tick.js:138)
    at process._tickCallback (internal/process/next_tick.js:180)

Always get an error

It seems that image has been optimized, but error is still thrown and process will exit.

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: ssim at q=50 (40 - 60): 0.996457
ssim at q=55 (51 - 60): 0.996672
ssim at q=58 (56 - 60): 0.997332
ssim at q=59 (59 - 60): 0.997369
ssim at q=60 (60 - 60): 0.997396
Final optimized ssim at q=61: 0.997048
New size is 47% of original (saved 63 kb)

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.