Coder Social home page Coder Social logo

mahnunchik / gulp-responsive Goto Github PK

View Code? Open in Web Editor NEW
504.0 9.0 61.0 280 KB

gulp-responsive generates images at different sizes

Home Page: https://npmjs.com/gulp-responsive

License: MIT License

JavaScript 100.00%
responsive-images responsive gulp sharp

gulp-responsive's Introduction

gulp-responsive Build Status

Greenkeeper badge

Generates images at different sizes

Installation

gulp-responsive depends on sharp. Sharp is one of the fastest Node.js modules for resizing JPEG, PNG, WebP and TIFF images.

If you are using Mac OS then before installing gulp-responsive you should install the libvips library. Further information and instructions can be found in the sharp installation guide.

$ npm install --save-dev gulp-responsive

Usage

var gulp = require('gulp')
var responsive = require('gulp-responsive')

gulp.task('default', function () {
  return gulp
    .src('src/*.{png,jpg}')
    .pipe(
      responsive({
        'background-*.jpg': {
          width: 700,
          quality: 50
        },
        'cover.png': {
          width: '50%',
          // convert to jpeg format
          format: 'jpeg',
          rename: 'cover.jpg'
        },
        // produce multiple images from one source
        'logo.png': [
          {
            width: 200
          },
          {
            width: 200 * 2,
            rename: '[email protected]'
          }
        ]
      })
    )
    .pipe(gulp.dest('dist'))
})

Integration

All together ๐ŸŽ†

API

responsive(config, options)

config

Configuration can be provided in one of the following formats:

1. Array of unique configurations
;[
  {
    name: 'logo.png',
    width: 200,
    height: 100
  },
  {
    name: 'banner.png',
    width: 500
  }
]
2. Object of unique configurations. Keys are filenames.
{
  'logo.png': {
    width: 300,
    height: 200,
    rename: '[email protected]'
  },
  'background-*.png': {
    width: 1400,
    withoutEnlargement: true
  }
}
3. Object of arrays of unique configurations. Keys are filenames.
{
  'logo.png': [{
      width: 200,
      rename: '[email protected]'
    },{
      width: 400,
      rename: '[email protected]'
    }],
  'background-*': [{
    height: 400
  }]
}

Configuration unit

Configuration unit is an object:

  • name: String โ€” filename glob pattern.
  • width: Number or String โ€” width in pixels or percentage of the original, not set by default.
  • height: Number or String โ€” height in pixels or percentage of the original, not set by default.
  • withoutEnlargement: Boolean โ€” do not enlarge the output image, default true.
  • skipOnEnlargement: Boolean โ€” do not write an output image at all if the original image is smaller than the configured width or height, default false.
  • min: Boolean โ€” preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to the width and height specified.
  • max: Boolean โ€” resize to the max width or height the preserving aspect ratio (both width and height have to be defined), default false.
  • quality: Number โ€” output quality for JPEG, WebP and TIFF, default 80.
  • progressive: Boolean โ€” progressive (interlace) scan for JPEG and PNG output, default false.
  • withMetadata: Boolean โ€” include image metadata, default false.
  • compressionLevel: Number โ€” zlib compression level for PNG, default 6.
  • rename: String, Object or Function โ€” renaming options, file will not be renamed by default. When extname is specified, output format is parsed from extension. You can override this autodetection with format option.
  • format: String โ€” output format jpeg, png, webp or raw, default is null.
  • crop: Crop the resized image to the exact size specified, default is false.
  • embed: Preserving aspect ratio, resize the image to the maximum width or height specified then embed on a background of the exact width and height specified, default is false.
  • ignoreAspectRatio: Boolean โ€” Ignoring the aspect ratio of the input, stretch the image to the exact width and/or height provided via resize, default is false.
  • kernel: String โ€” The kernel to use for image reduction, defaulting to lanczos3.
  • background: Color โ€” Set the background for the embed and flatten operations, '#default is fff'.
  • flatten: Boolean โ€” Merge alpha transparency channel, if any, with background, default is false.
  • negate: Boolean โ€” Produces the "negative" of the image, default is false.
  • rotate: Boolean โ€” Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag, default is false.
  • flip: Boolean โ€” Flip the image about the vertical Y axis. This always occurs after rotation, if any. The use of flip implies the removal of the EXIF Orientation tag, if any. Default is false.
  • flop: Boolean โ€” Flop the image about the horizontal X axis. This always occurs after rotation, if any. The use of flop implies the removal of the EXIF Orientation tag, if any. Default is false.
  • blur: Boolean โ€” When used without parameters, performs a fast, mild blur of the output image. This typically reduces performance by 10%. Default is false.
  • sharpen: Boolean โ€” When used without parameters, performs a fast, mild sharpen of the output image. This typically reduces performance by 10%. Default is false.
  • threshold: Number or Boolean โ€” Converts all pixels in the image to greyscale white or black, default is false.
  • gamma: Boolean โ€” Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma then increasing the encoding (brighten) post-resize at a factor of gamma. Default is false.
  • grayscale: Boolean โ€” Convert to 8-bit greyscale; 256 shades of grey, default is false.
  • normalize: Boolean โ€” Enhance output image contrast by stretching its luminance to cover the full dynamic range. This typically reduces performance by 30%. Default is false.
  • trim: Boolean or Number โ€” Trim "boring" pixels from all edges that contain values within a percentage similarity of the top-left pixel. Default is false.
  • tile: Boolean or Object โ€” The size and overlap, in pixels, of square Deep Zoom image pyramid tiles, default is false.
  • withoutChromaSubsampling: Boolean โ€” Disable the use of chroma subsampling with JPEG output (4:4:4), default is false.

Detailed description of each option can be found in the sharp API documentation.

Renaming

Renaming is implemented by the rename module. Options correspond with options of gulp-rename.

options

errorOnUnusedConfig

Type: Boolean
Default: true

Emit the error when configuration is not used.

errorOnUnusedImage

Type: Boolean
Default: true

Emit the error when image is not used.

passThroughUnused

Type: Boolean
Default: false

Keep unmatched images in the stream. To use this option errorOnUnusedImage should be false.

errorOnEnlargement

Type: Boolean
Default: true

Emit the error when image is enlarged.

stats

Type: Boolean
Default: true

Show statistics after the run โ€” how many images were created, how many were matched and how many were in the run in total.

silent

Type: Boolean
Default: false

Silence messages and stats if 0 images were created. If you wish to supress all messages and stats, set the options.stats to false as well.

You can specify global default value for any of the configuration options.

gulp.task('default', function () {
  return gulp
    .src('src/*.png')
    .pipe(
      responsive(config, {
        // global quality for all images
        quality: 50,
        errorOnUnusedImage: false
      })
    )
    .pipe(gulp.dest('dist'))
})

License

MIT ยฉ Evgeny Vlasenko

gulp-responsive's People

Contributors

adamkiss avatar addyosmani avatar astorsoft avatar birnbaum avatar dandaka avatar felthy avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jhby1 avatar joranrood avatar luksm avatar mahnunchik avatar rejas avatar sirlisko avatar starptech avatar subblue avatar thedancingcode 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

gulp-responsive's Issues

Not working with subfolders

Expected behaviour:

  1. gulp-responsive takes files from subfolders
  2. transforms them
  3. puts in subfolders in the output folder

Code:

gulp.task('responsive2', function () {
  gulp.src('./src/img/**/*.jpg')
    .pipe(print())
    .pipe(responsive([{
      name: 'banner.jpg',
      width: 600
      }],
      {
        errorOnUnusedImage: false
      }
    ))
    .pipe(gulp.dest('./public/img/'));
});

Log:

[frontend-boilerplate] gulp responsive2                               master  โœญ
[15:31:46] Using gulpfile ~/projects/frontend-boilerplate/gulpfile.js
[15:31:46] Starting 'responsive2'...
[15:31:46] Finished 'responsive2' after 9.45 ms
[15:31:46] src/img/imgs/banner.jpg

stream.js:75
      throw er; // Unhandled stream error in pipe.
      ^
Error: Available images do not match following config:
  - `banner.jpg`

Version 2.0

Roadmap

Add more sharp methods

Add the ability to transform format of output image

  • format detection by the filename (rename option)
  • force format option

Add better usage examples #16

Misc

  • Add visibility to image manipulation process

Cannot convert JPG files: Error: Input buffer contains unsupported image format

While it converts PNG images without any problem,
It cannot convert any jpg/jpeg image,

I get this error:

File foo.jpg: Input buffer contains unsupported image format

images are valid,

$ identify assets/images/foo.jpg 
assets/images/foo.jpg JPEG 1600x901 1600x901+0+0 8-bit sRGB 222KB 0.000u 0:00.000

this is the task

var plumber = require('gulp-plumber');
// Test subfolders
gulp.task('responsive-subfolders', function () {
  gulp.src(['./assets/images/**/*.{jpg,png}'])
  .pipe(plumber())
  .pipe(responsive(
    {
      '**/*.png': {
        width: 16,
        quality: 80,
      },
      '**/*.jpg': {
        width: 200,
        quality: 80,
      }
    }, {
      errorOnUnusedConfig: false,
      errorOnUnusedImage: false,
      errorOnEnlargement: false,
    }
  ))
  .pipe($.plumber())
  .pipe(gulp.dest('./tmp/'));
});

and here's the full error with gulp-plumber

[02:37:34] Plumber found unhandled error:
 Error in plugin 'gulp-responsive'
Message:
    File `foo.jpg`: Input buffer contains unsupported image format
quality: use jpeg({ quality: ... }), webp({ quality: ... }) and/or tiff({ quality: ... }) instead
progressive: use jpeg({ progressive: ... }) and/or png({ progressive: ... }) instead
withoutChromaSubsampling: use jpeg({ chromaSubsampling: "4:4:4" }) instead
compressionLevel: use png({ compressionLevel: ... }) instead

wondering if there is something wrong with my system

Blurring with a sigma

I am trying to blur an image with a provided sigma, currently in the docs it says that this is a Boolean. Is there a way to have this take a custom sigma value as well?

If I try

{
    width: 20,
    rename: { suffix: '-placeholder' },
    blur: [200],
    grayscale: true
}

I get this error via the cli (which I guess is normal as this is not a true or false input

Message:
    File `qsdfqsdf.jpg`: Invalid blur sigma (0.3 - 1000.0) 200
Details:
    domainEmitter: [object Object]
    domain: [object Object]
    domainThrown: false
Stack:
Error: File `qsdfqsdf.jpg`: Invalid blur sigma (0.3 - 1000.0) 200
    at Sharp.blur (C:\xampp\htdocs\sandbox - gulp 4\tools\node_modules\sharp\index.js:498:11)
    at C:\xampp\htdocs\sandbox - gulp 4\tools\node_modules\gulp-responsive\lib\sharp.js:121:13

Feature request: batch resize

Following on from #3 (percentage resize) it'd be nice to be able to batch resize a group of images, by writing something like:

.pipe(responsive({
  '*.png': [{
      width: 50%,
    },{
      width: 100%,
      rename: '*@2x.png'
    }],
  '*.jpg': [{
      width: 50%,
    },{
      width: 100%,
      rename: '*@2x.jpg'
    }]
}))

or even just

.pipe(responsive({
  '*.*': [{
      width: 50%,
    },{
      width: 100%,
      rename: '*@2x.*'
    }]
}))

^ the holy grail of gulp image tasks if you as me :D
Could maybe be written in a tidier manner though

An in-range update of jshint is breaking the build ๐Ÿšจ

Version 2.9.5 of jshint just got published.

Branch Build failing ๐Ÿšจ
Dependency jshint
Current Version 2.9.4
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As jshint is โ€œonlyโ€ a devDependency of this project it might not break production or downstream projects, but โ€œonlyโ€ your build or test tools โ€“ preventing new deploys or publishes.

I recommend you give this issue a high priority. Iโ€™m sure you can resolve this ๐Ÿ’ช

Status Details
  • โŒ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Release Notes JSHint 2.9.5

2.9.5 (2017-06-22)

Bug Fixes

  • Account for hoisting of importing bindings (bd36953)
  • Add onmessage to vars.worker (540ed85)
  • Added missing "Storage" browser variable (8cfe5ad)
  • Avoid crash when peeking past end of prog (c083866)
  • Avoid false positive (44d9e0b)
  • Close synthetic scope for labeled blocks (5f0f789)
  • Fail gracefully on invalid if syntax (#3103) (8c6ac87)
  • Honor "ignore" file when linting STDIN (d4f83a4)
  • Parse for-in/of head LHS as asnmt target (da52ad9)
  • Removed warning message W041 (#3115) (376fa62)
  • Throw W033 instead of E058 when the ; after a do-while stmt is missing (6907cd4)

Features

Commits

The new version differs by 42 commits.

  • d3d84ae v2.9.5
  • 481cdca Merge branch 'W083'
  • ad7df61 [[TEST]] Update tests to reflect new W083 language
  • 5967e61 [[TEST]] Less ambiguous message for W083
  • cc215bd [[CHORE]] Update Test262
  • e6c89f0 [[CHORE]] Fix bug in test script
  • 5b957f6 Merge pull request #3126 from jugglinmike/for-lhs
  • da52ad9 [[FIX]] Parse for-in/of head LHS as asnmt target
  • b075919 [[FEAT]] Add MediaRecorder to vars.js
  • 24b8c97 Merge pull request #3066 from jugglinmike/asi-dowhile-es6-updated
  • 29c359f Merge pull request #3064 from jugglinmike/improve-yield-messages
  • c083866 [[FIX]] Avoid crash when peeking past end of prog
  • 5f0f789 [[FIX]] Close synthetic scope for labeled blocks
  • 70f9ca2 Merge remote-tracking branch 'jugglinmike/2358-improve-unused-desc'
  • bd36953 [[FIX]] Account for hoisting of importing bindings

There are 42 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot ๐ŸŒด

Error on Install: node-gyp rebuild

Getting an error when trying to install into a new project.

$ npm install --save-dev gulp-responsive

> [email protected] install /PROJECT_PATH/node_modules/gulp-responsive/node_modules/sharp
> node-gyp rebuild

Package vips was not found in the pkg-config search path.
Perhaps you should add the directory containing `vips.pc'
to the PKG_CONFIG_PATH environment variable
No package 'vips' found
gyp: Call to 'PKG_CONFIG_PATH="/usr/lib/pkgconfig:/usr/local/Library/ENV/pkgconfig/10.10:$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig" pkg-config --libs vips' returned exit status 1. while trying to load binding.gyp
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:357:16)
gyp ERR! stack     at ChildProcess.emit (events.js:110:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:1074:12)
gyp ERR! System Darwin 14.5.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /PROJECT_PATH/node_modules/gulp-responsive/node_modules/sharp
gyp ERR! node -v v0.12.7
gyp ERR! node-gyp -v v2.0.2
gyp ERR! not ok 
npm ERR! Darwin 14.5.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "--save-dev" "gulp-responsive"
npm ERR! node v0.12.7
npm ERR! npm  v2.14.2
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the sharp package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls sharp
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /PROJECT_PATH/npm-debug.log

Currently using node v0.12.7 and npm 2.14.2 on Mac 10.10.5 Yosemite.

Resize based on image orientation.

It would be cool to have an option to resize images at different sizes based on whether they are portrait or landscape oriented images. I didn't seem an option for this so I assume it isn't currently possible.

Processs newer images only

It would be very helpful to have an option to only process files that do not exist in dest, or that are newer than those in dest.

I tried piping through gulp-newer but got the following error: Expected a source file with stats

Leave out compression

I really just need this excellent plugin for generating responsive images. I'm using imagemin for handling compression since it also compresses svgs. Is there anyway of disabling compression with gulp-responsive? When compression is unspecified, I think this plugin uses 70% quality. Otherwise, if I change compression to 100% quality, it still compresses the file and inflates it by almost twice the file size.

Output files not ending up in subfolders

I've got some POC code, that looks like this:

gulp.task('responsive-images', function () {
  return gulp.src(['public/**/logo-square.png'])
    .pipe(responsive({
      // produce multiple images from one source
      '**/*.png': [
        {
          width: '100%',
          rename: '[email protected]'
        }
      ]
    }))
    .pipe(gulp.dest('staging'));
});

Inside the source directory, the path where images might be found are various event subfolders (for example, public/events/hoofington-2017, etc.

The output I get from gulp is this:

[17:44:44] gulp-responsive: events/2016-berlin/logo-square.png -> [email protected]
[17:44:44] gulp-responsive: events/2016-brasilia/logo-square.png -> [email protected]
[17:44:44] gulp-responsive: events/2016-telaviv/logo-square.png -> [email protected]
[17:44:44] gulp-responsive: events/2016-warsaw/logo-square.png -> [email protected]
[17:44:44] gulp-responsive: events/2017-amsterdam/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-austin/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-baltimore/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-charlotte/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-hoofington/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-minneapolis/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-moscow/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-ponyville/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-salt-lake-city/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-seattle/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: events/2017-zurich/logo-square.png -> [email protected]
[17:44:45] gulp-responsive: Created 15 images (matched 15 of 15 images)

And the only generated image is at the root of staging and is [email protected]. None of the events/2017-moscow etc folders get populated.

I'm not quite sure why this is happening. I know that right now it's not really doing anything interesting but renaming the file, but this was my attempt to at least see the subfolders work.

processing in subfolders

I can't make gulp-responsive process subfolders. Here's my code:

gulp.task('resize-all', function () {
  gulp.src('_img/**/*')
    .pipe(responsive({
      '*.jpg': [{
        width: 2048,
        suffix: '-2048'
      }, {
        width: 1536,
        suffix: '-1536'
      }, {
        width: 1080,
        suffix: '-1080'
      }, {
        width: 750,
        suffix: '-750'
      }, {
        width: 320,
        suffix: '-320'
      }]
    }))
    .pipe(gulp.dest('_site/img'));
});

Handling Segmentation fault: 11

I've been getting a sporadic Segmentation fault: 11 error when using gulp-responsive.
My task is using a */.jpg source path to match a bunch of images in subfolders. Sometimes it would complete the task without problems, but other times it throws the error.

Running the task on specific subfolders individually always worked, but then it occurred to me that it might be Dropbox interfering with the files before they have been fully written to disk as pausing Dropbox seems to stop the error. I'll probably end up modifying my task to move the files outside my Dropbox folder for the resizing so that I can keep my usual workflow.

I'm using OSX 10.10.1 and the issue is probably something to do with Sharp rather than gulp-responsive, but in case others have the same problem I thought it worth mentioning here.
Is there a way of more gracefully capturing such errors I wonder?

Quality option has no effect, my images end up being larger

My original hero image: 1600 x 672 hero.jpg, it's 1MB, after the gulp-responsive with the below task it's 1.2MB 1600 x 672 hero-1030-2x.jpg. I set the quality intentionally low but doesn't seem to have any effect on the image. The size 1030 * 2 is over the original in this case but it's not enlarged, withoutEnlargement doesn't also seem to have any effect. Is this the right way to do the configuration?

'use strict';
var gulp = require('gulp'),
    responsive = require('gulp-responsive'),
    config = require('../config.gulp').images;

gulp.task('images:resize', function() {
    return gulp.src(config.bigImgs)
        .pipe(responsive({
            // Big images with multiple sizes
            '**/*-hero.jpg': [{
                width: 600,
                rename: {suffix: '-600-1x'}
            }, {
                width: 600 * 2,
                rename: {suffix: '-600-2x'}
            }, {
                width: 786,
                rename: {suffix: '-786-1x'}
            }, {
                width: 786 * 2,
                rename: {suffix: '-786-2x'}
            }, {
                width: 1030,
                rename: {suffix: '-1030-1x'}
            }, {
                width: 1030 * 2,
                rename: {suffix: '-1030-2x'},
                quality: 40
            }],
            // Smaller images that only need retina versions
            '**/*-ret.{jpg,png}': [{
                width: '50%',
                rename: {suffix: '-1x'}
            }],
            // Really small images that only need retina versions
            '**/*-small.{jpg,png}': [{
                width: '75',
                rename: {suffix: '-75-1x'}
            }, {
                width: '150',
                rename: {suffix: '-75-2x'}
            }]
        }, {
            quality: 40,
            errorOnUnusedImage: false,
            errorOnEnlargement: false,
            withoutEnlargement: true,
            progressive: true,
            withMetadata: false
        }))
        .pipe(gulp.dest(config.dest));
});

update sharp v0.17

previous settings issue:

vips warning: VipsJpeg: error reading resolution
(node:22753) DeprecationWarning: quality: use jpeg({ quality: ... }), webp({ quality: ... }) and/or tiff({ quality: ... }) instead
(node:22753) DeprecationWarning: progressive: use jpeg({ progressive: ... }) and/or png({ progressive: ... }) instead
(node:22753) DeprecationWarning: withoutChromaSubsampling: use jpeg({ chromaSubsampling: "4:4:4" }) instead
vips warning: VipsJpeg: error reading resolution
(node:22753) DeprecationWarning: compressionLevel: use png({ compressionLevel: ... }) instead
vips warning: VipsJpeg: error reading resolution

I tried to correct the settings on the:

param.jpeg = {progressive: true};
param.png = {progressive: true};

warnings remained.
how to fix?

An in-range update of mocha is breaking the build ๐Ÿšจ

Version 3.4.0 of mocha just got published.

Branch Build failing ๐Ÿšจ
Dependency mocha
Current Version 3.3.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As mocha is โ€œonlyโ€ a devDependency of this project it might not break production or downstream projects, but โ€œonlyโ€ your build or test tools โ€“ preventing new deploys or publishes.

I recommend you give this issue a high priority. Iโ€™m sure you can resolve this ๐Ÿ’ช

Status Details
  • โŒ continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes v3.4.0

Mocha is now moving to a quicker release schedule: when non-breaking changes are merged, a release should happen that week.

This week's highlights:

  • allowUncaught added to commandline as --allow-uncaught (and bugfixed)
  • warning-related Node flags

๐ŸŽ‰ Enhancements

๐Ÿ› Fixes

๐Ÿ”ฉ Other

Commits

The new version differs by 9 commits0.

  • 7554b31 Add Changelog for v3.4.0
  • 9f7f7ed Add --trace-warnings flag
  • 92561c8 Add --no-warnings flag
  • ceee976 lint test/integration/fixtures/simple-reporter.js
  • dcfc094 Revert "use semistandard directly"
  • 93392dd no special case for macOS running Karma locally
  • 4d1d91d --allow-uncaught cli option
  • fb1e083 fix allowUncaught in browser
  • 4ed3fc5 Add license report and scan status

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot ๐ŸŒด

Multiple output formats

The picture element can be used together with srcset to provide multiple image formats (notably webp + png as fallback), it would be great if gulp-responsive could output the same image in multiple formats.

The format option expects a string, for multiple formats, it would make sense letting it expect an array.
It is possible to have multiple output formats with current gulp-responsive,
but this requires redundant configuration.

Allow kernel options.

I noticed this plugin forwards interpolation to sharp interpolator to configure how enlarging images is handled but doesn't forward kernel to configure how reducing images is handled.

Not getting output from gulp-responsive

Moving from Grunt to Gulp and trying to undestand what's going on.

Task I'm running

gulp.task('images', function () {
  return gulp.src('[app/images/**/*.{jpg,png}]')
    .pipe($.responsive({
      // Resize all JPG images to three different sizes: 200, 500, and 630 pixels
      '*.jpg': [{
        width: 200,
        rename: { suffix: '-200px' }
      }, {
        width: 500,
        rename: { suffix: '-500px' }
      }, {
        width: 630,
        rename: { suffix: '-630px' }
      }, {
        // Compress, strip metadata, and rename original image
        rename: { suffix: '-original' }
      }],
      // Resize all PNG images to be retina ready
      '*.png': [{
        width: 250
      }, {
        width: 250 * 2,
        rename: { suffix: '@2x' }
      }]
    }, {
      // Global configuration for all images
      // Strip all metadata
      withMetadata: false
    }))
    .pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [ mozjpeg() ]
    }))
    .pipe(webp({quality: 50})())
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({
      pretty: true,
      title: 'processImages'
    }));
});

With the command above I get the following error

16:51:50] carlos@Rivendell athena-shell 1945$ gulp images
[16:53:51] Using gulpfile ~/code/athena-shell/gulpfile.js
[16:53:51] Starting 'images'...
[16:53:51] 'images' errored after 119 ms
[16:53:51] Error in plugin 'gulp-responsive'
Message:
Available images do not match the following config:

  • *.jpg
  • *.jpg
  • *.jpg
  • *.jpg
  • *.png
  • *.png

If I comment out the pipe commands after responsive the command start but fails silently and exits.

output of gulp images command
[16:39:19] carlos@Rivendell images 1938$ gulp images
[16:41:44] Working directory changed to ~/code/athena-shell
[16:41:46] Using gulpfile ~/code/athena-shell/gulpfile.js
[16:41:46] Starting 'images'...
[16:41:47] carlos@Rivendell images 1939$

gulp --version
CLI version 3.9.0
Local version 3.9.1

node --version
v5.6.0

version of Vips
[16:41:47] carlos@Rivendell images 1939$ vips --version
vips-8.2.2-Tue Jan 26 13:54:33 PST 2016

Installed via Homebrew on a Mac

What am I doing wrong? how do I fix this?

PNG are twice bigger than with imageMagick

The PNG output of gulp-responsive are twice bigger than what I get from grunt-responsive (which is using imageMagick).

152x174 image > 3.5KB with imageMagick, 7KB with gulp responsive

With these settings it's a little bit better at 6.7KB
progressive: true,
compressionLevel: 9,
errorOnUnusedConfig: false,
errorOnUnusedImage: false,
errorOnEnlargement: false

imagemin passthrough / Add optimiseScans option

With libvips with mozjpeg, an extra pass to imagemin-mozjpeg isn't required,
it would be nice to have this option supported by gulp-responsive.
http://sharp.dimens.io/en/stable/api-output/#jpeg

Alternatively, it would also be nice to pass imagemin configuration
(e.g. specific imagemin-mozjpeg or imagemin-pngquant (for lossy PNG compression) configuration),
currently I have to gulp-filter, imagemin and gulp-filter.restore for each image-set:

[...]
         .pipe(plugins.responsive([...]))
         .pipe(filterFirstSetPng)
         .pipe(plugins.imagemin([plugins.imagemin.optipng({optimizationLevel: 7})]))
         .pipe(filterFirstSetPng.restore)
         .pipe(filterFirstSetWebp)
         .pipe(plugins.imagemin([imageminWebp({preset: 'photo'})]))
         .pipe(filterFirstSetWebp.restore)
[...]

Glob patterns do not match any image within the source src directory

Hi I have followed whatever documentation is available from the readme here and configured mu gulpfile like so:

**

var $ = require('gulp');
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
var responsive = require('gulp-responsive');

**

$.task('responsive-images', function() {
    $.src('images_src/*.jpg').pipe(responsive({
        '*.jpg': [{
                width: 480,
                rename: false
            }, {
                width: 640,
                rename: false
            } ]
    }, {
        quality: 50,
        progressive: true
    })).pipe($.dest('build/images/'));
});

The pattern match string in $.src('images_src/*.jpg) is not working. No files are matched

Errors if unsupported file type found

I usually have a bunch of svgs in my images directory which are processed by my image task - would be more robust if it simple skipped unsupported formats? Of course I can pipe/filter just the required file formats, but that seems less than ideal (for example I'm also piping svgs to gulp-imagemin)

        throw er; // Unhandled 'error' event
              ^
Error: Image does not match any config: imagename.svg

Skip on enlargement

When I set one of these parameters: withoutEnlargement / skipOnEnlargement to true (or both of them), my gulp task processes a portion of images and stops (with no special errors). It does skip files that are smaller then resize options and prints notifications about it to console, but it doesn't process ALL the images.

If I set both options to false, all images are processed with no problems. But, of course, some happen to be enlarged for no reason, I don't like that.

I do have a plumber.

Here's my code:

    gulp.task('resize-jpg', function() {
      return gulp.src('_img/**/*.jpg')
        .pipe(plumber())
        .pipe(gulpResponsive({
          '**/*.jpg': [{
            width: 2048,
            withoutEnlargement: true,
            skipOnEnlargement: true,
            progressive: true,
            quality: 70,
            rename: {
              suffix: '-2048'
            }
          }, {
            width: 1536,
            withoutEnlargement: true,
            skipOnEnlargement: true,
            progressive: true,
            quality: 70,
            rename: {
              suffix: '-1536'
            }
          }, {
            width: 1080,
            withoutEnlargement: true,
            skipOnEnlargement: true,
            progressive: true,
            quality: 70,
            rename: {
              suffix: '-1080'
            }
          }, {
            width: 750,
            withoutEnlargement: true,
            skipOnEnlargement: true,
            progressive: true,
            quality: 70,
            rename: {
              suffix: '-750'
            }
          }, {
            width: 320,
            withoutEnlargement: true,
            skipOnEnlargement: true,
            progressive: true,
            quality: 70,
            rename: {
              suffix: '-320'
            }
          }]
        }))
        .pipe(gulp.dest('dest/img'));
    });

Can't filter with gulp-changed or gulp-newer

gulp-file.js

var gulp = require('gulp'),
    responsive = require('gulp-responsive'),
    $          = require('gulp-load-plugins')(),
    sizes      = [0.75, 0.5, 0.25, 0.2, 0.15, 0.1, 0.05];

gulp.task('misc', function () {
  var dest = 'dist/misc';
  return gulp.src(['originals/misc/*.png'])
    .pipe($.newer(dest))
    .pipe(gulp.dest(dest))
    .pipe(responsive({
      '*.png': sizes.map(function(size) {
        return {
          width: '' + (size * 100) + '%',
          rename: {
            suffix: size === 1 ? '' : ('@' + size + 'x'),
          }
        }
      })
    }))
    .pipe(gulp.dest(dest));
});

When filtering with newer or changed, I get the following error:

[17:33:39] Starting 'misc'...
[17:33:39] gulp-responsive: Created 0 images (matched 0 of 0 images)

stream.js:74
      throw er; // Unhandled stream error in pipe.
      ^
Error: Available images do not match the following config:
  - `*.png`
  - `*.png`
  - `*.png`
  - `*.png`
  - `*.png`
  - `*.png`
  - `*.png`

Any idea why it is not ignoring the filtered items?

Rename extension according to output format

Right now

  1. Take folder of PNG files
  2. Convert them to JPG files
  3. Names are preserved (*.png)

Should be

  1. Additional option "extensionMatchOutput", defaults: true
  2. When true, output files extension are named according to output format

Crop

How does one use the crop option?

thnx

Unable to install from NPM

Currently getting the following error when I try to run ``npm install gulp-responsive`.

fetch failed https://registry.npmjs.org/gulp-responsive/-/gulp-responsive-1.1.0.tgz
npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 404

ps. Congrats on the new release

Do I have to add a global config?

Hi,

Will it be useful to add global config? For example, in this case quality overrides:

gulp.src('src/*.jpeg')
  .pipe(responsive([{
    name: 'logo.jpeg',
    width: 200
  },{
    name: 'logo.jpeg',
    width: 200 * 2,
    rename: '[email protected]'
  },{
    name: 'background-*.jpeg',
    width: 700,
    // local
    quality: 70
  }],{
    // global
    quality: 95
  }))
  .pipe(gulp.dest('dist'));

Some images to jpg, some to png

This is not a task, but rather a question.

Use case. Some images are better (smaller size and less compression artifacts) to be converted to PNG (graphics), some to JPG (photos). Usual scenario is like this:

  1. Have a look at images
  2. Specify which output as JPG, which as PNG. Right now the best solution is to make this decision before going to gulp-responsive in file extensions. So *.PNG โ†’ *.PNG, *.JPG โ†’ *.JPG. Alternative is configuration in JSON (either gulpfile.js or each folder), which is more complicated to setup.

How do you config such cases? Maybe there is another hidden option inside next branch, that should be documented :)

To make it more automatic, we could use https://github.com/Huddle/Resemble.js to analyse artefacts (difference) from different output. And select optimal. But this sounds like a huge task with big risks.

crashes if image is too small

events.js:160
      throw er; // Unhandled 'error' event
      ^
Error: File `X_logo.jpg`: Image enlargement is detected
  real width: 153px, required width: 200px

(sharp:3559): GLib-CRITICAL **: g_hash_table_lookup: assertion 'hash_table != NULL' failed

(sharp:3559): GLib-CRITICAL **: g_hash_table_lookup: assertion 'hash_table != NULL' failed

(sharp:3559): GLib-CRITICAL **: g_hash_table_lookup: assertion 'hash_table != NULL' failed

(sharp:3559): GLib-CRITICAL **: g_hash_table_lookup: assertion 'hash_table != NULL' failed

(sharp:3559): GLib-CRITICAL **: g_hash_table_lookup: assertion 'hash_table != NULL' failed

Error: File 'myImage.png': VipsOperation: class "webpsave_buffer" not found

When I try to create webp images, I get the following error message:
Error: File 'myImage.png': VipsOperation: class "webpsave_buffer" not found

I am able to create jpg and png images successfully.

I'm on:
Windows 10
Node v5.9.1

Here's the configuration I'm using:

{
  width: 200,
  rename: {
    suffix: '-small',
    extname: '.webp'
  }
}

Sharp deprecation warnings

Deprecation warnings from sharp are logged when running gulp-responsive:

[...]
quality: use jpeg({ quality: ... }), webp({ quality: ... }) and/or tiff({ quality: ... }) instead
progressive: use jpeg({ progressive: ... }) and/or png({ progressive: ... }) instead
withoutChromaSubsampling: use jpeg({ chromaSubsampling: "4:4:4" }) instead
compressionLevel: use png({ compressionLevel: ... }) instead
[...]

See also at https://github.com/lovell/sharp/blob/master/lib/output.js#L429.

Better usage examples

Hi Could you provide some better examples? It's not clear to me how you would take, say, a directory of images with similar file names and generate responsive images from a template of sizes. I am planning to test a bit, but it would be great to have better docs.

Bug if he doesn't found a file

Hi,
I have a simple task but gulp bug when he doesn't found any file with .png :

gulp.task('tasks0', ['task'],  function(){

  return gulp.src('app/assets/img/upload/other/*.{png,jpg,jpeg}')
  .pipe(responsive({
      // produce multiple images from one source
      '*.jpg':
        {
          width: 720,
          withoutEnlargement:false,
          progressive: true,
          quality:70
        },
      '*.png':
        {
          width: 720,
          progressive:true,
          compressionLevel : 7,
          withoutEnlargement:true
        },
      '*':
      {
        width: 720,
        progressive:true,
        withoutEnlargement:false
      }
    }))
  .pipe(gulp.dest('app/assets/img/upload/other/'));
}
); 

Regards
Quentin

Feature Request: Suffix

I just took a quick look at this, but is there an easy way to just add a suffix to the name, like suffix: "-small"?

Also, there is a typo in your readme: "raname".

Prevent processing unenlarged file without an error?

Hi there! Love this plugin.

I want to use gulp-responsive to batch-resize all images within a given directory to be resized down to several different sizes, for use with picturefill/srcset. I've noticed, however, that gulp-responsive will create new copies of a file with the same pixel dimensions if an option block defines a width target higher than the original source file.

How do I configure gulp-responsive to simply skip a config block if the original image is smaller than the destination output width of that config block?

I've set withoutEnlargement to true to at least prevent gulp-responsive from enlarging the images, but I hoped it would also cause the plugin to skip any images bigger than the config block.

Below, I've pasted my default config block.

gulp.task('images', function() {
  browserSync.notify('Responsive images starting.');
  return gulp.src('images-source/**/*.{jpg,jpeg,png,tiff,webp,gif}')
    .pipe(newer('./html/images-build'))
    .pipe(plumber())
    .pipe(responsive({
      '**/*.{jpg,png,tiff,webp,gif}': [{
          width: 320,
          rename: {
            suffix: "-320"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          width: 480,
          rename: {
            suffix: "-480"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          width: 640,
          rename: {
            suffix: "-640"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          width: 800,
          rename: {
            suffix: "-800"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          width: 1024,
          rename: {
            suffix: "-1024"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          width: 1280,
          rename: {
            suffix: "-1280"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          width: 1600,
          rename: {
            suffix: "-1600"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          width: 1890,
          rename: {
            suffix: "-1890"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          width: 2400,
          rename: {
            suffix: "-2400"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      },{
          rename: {
            suffix: "-original"
          },
          withoutEnlargment: true,
          passThroughUnused: false
      }]
    }))
    .pipe(gulp.dest('./html/images-build'));
});

Thanks!

Support subfolder **/* glob pattern?

I've organized a bunch of images into subfolders and am trying to do a batch resize of them. I've tried using the subfolder **/* glob pattern in the source, but it doesn't seem to work. Below is my config:

gulp.src(['_source/assets/images/**/*.jpg'])
    .pipe(responsive(
    {
        '*.jpg':
        [{
            width: 160,
            rename:
            {
                suffix: '--mini'
            }
        }]
    },
    {
        strictMatchImages: false,
        strictMatchConfig: false
    }))
.pipe(gulp.dest('images'));

When I run the task with strictMatchConfig set to true I get the error:

stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
Error: Available images do not match following config:
  - `*.jpg`

When set to false the error doesn't show, as expected, but either way all images in the subfolders are ignored.

Changing the src to one of the subfolders like _source/assets/images/portraits/*.jpg runs fine.

Am I doing something wrong or is there a workaround? I appreciate any help.

background-*.jpg is not working

If no pictures the mask background-*.jpg or *, the task results in an error.
the task must be turned off manually until it is needed and should include when the pictures appear.

Error:

Message:
    Available images do not match the following config:
  - `background-*.jpg`
  - `background-*.jpg`
  - `background-*.jpg`
Details:
    domainEmitter: [object Object]
    domain: [object Object]
    domainThrown: false

Please add the correct handling of such situations without completing the task fail.
Thank you! :)

PNGs are becoming larger

Even with compressionLevel: 9, my PNGs are actually getting larger. Any way to ameliorate this?

Select format output per image

Do I understand correctly, that right now it is impossible to force output format? Say, take 10 PNG images and convert them to JPG?

Sharp has this feature
http://sharp.dimens.io/en/stable/api/#toformatformat

I have tried toFormat in config JSON with no result

  gulp.src('./src/img/05OC/*.png')
    .pipe(print())
    .pipe(responsive([{
      name: '*.png',
      width: 600,
      toFormat: 'jpeg'
    }],
    {
      errorOnUnusedImage: false
    }
    ))
    .pipe(gulp.dest('./public/img/'));
});

gulp-responsive runs before previous pipe is complete

This is a question, not an issue.

I have one gulp task that first pipes gulp-tap, then pipes gulp-responsive.

The width I would like to use for one size of images is included in the image file name. I use gulp-tap to read the file path. Then I extract the dimensions from the file path and add that value to a global "width" variable.

Then, I pipe gulp-responsive. I use the global width variable as one of the image width settings.

The issue is that the second pipe (gulp-responsive) runs before the width variable value is set in the first pipe. So, the gulp-responsive width setting gets a value of undefined instead of the desired value.

Is there a way that I can prevent gulp-responsive from running until the previous pipe is complete?

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.