Skip to content

Instantly share code, notes, and snippets.

@ddprrt

ddprrt/images.js Secret

Created August 3, 2016 10:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ddprrt/1b535c30374158837df89c0e7f65bcfc to your computer and use it in GitHub Desktop.
Save ddprrt/1b535c30374158837df89c0e7f65bcfc to your computer and use it in GitHub Desktop.
GM/Gulp
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var newer = require('gulp-newer');
var filter = require('gulp-filter');
var merge = require('merge2');
var rename = require('gulp-rename');
var resize = require('./resize-images')
var options = [
{ width: 200, upscale: false },
{ width: 400, upscale: false },
{ width: 600, upscale: false },
{ width: 800, upscale: false },
{ width: 1000, upscale: false },
{ width: 1200, upscale: false },
{ width: 1400, upscale: false },
{ width: 1600, upscale: false }
]
gulp.task('images', function() {
var streams = options.map(function(el) {
return gulp.src(['./_images/**/*', '!./_images/**/*.svg'])
.pipe(rename(function(file) {
if(file.extname) {
file.basename += '-' + el.width
}
}))
.pipe(newer('images'))
.pipe(resize(el))
.pipe(imagemin())
.pipe(gulp.dest('images'));
});
streams.push(gulp.src('_images/**/*')
.pipe(newer('images'))
.pipe(imagemin())
.pipe(gulp.dest('images')));
return merge(streams);
});
var gm = require('gm');
var through = require('through2');
module.exports = function(el) {
return through.obj(function(originalFile, enc, cb) {
var file = originalFile.clone({contents: false});
if (file.isNull()) {
return cb(null, file);
}
var gmfile = gm(file.contents, file.path);
gmfile.size(function(err, size) {
if(typeof el !== 'undefined' && el.width < size.width) {
gmfile
.resize(el.width, (el.width / size.width) * size.height)
.toBuffer(function (err, buffer) {
file.contents = buffer;
cb(null, file);
});
} else {
// remove from stream
cb(null, null);
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment