Skip to content

Instantly share code, notes, and snippets.

@dturton
Created May 5, 2015 16:26
Show Gist options
  • Save dturton/f30cc75ed3772829e63e to your computer and use it in GitHub Desktop.
Save dturton/f30cc75ed3772829e63e to your computer and use it in GitHub Desktop.
Gulp image resize/optimize
// require gulp plugins
var gulp = require('gulp');
var imageresize = require('gulp-image-resize');
var imagemin = require('gulp-imagemin');
var watermark = require("gulp-watermark");
var rename = require("gulp-rename");
var gulpif = require('gulp-if');
var paths = {
folder: '',
src: './batch/src/*',
dest: './batch/dist/'
}
// create an array of image groups (see comments above)
// specifying the folder name, the ouput dimensions and
// whether or not to crop the images
var images = [
{ folder: 'lg', width: 1200, crop: false, watermark: false },
{ folder: 'weblg', width: 1200, crop: false, prefix: 'w', watermark: true },
{ folder: 'thumb', width: 275, height: 275, crop: false, prefix: 't', suffix: '_thumb', watermark: false},
{ folder: 'webthumb', width: 170, height: 170, crop: false, prefix: 'w', suffix: '_sm', watermark: false}
];
// images gulp task
gulp.task('default', function () {
// loop through image groups
images.forEach(function(type){
// build the resize object
var resize_settings = {
width: type.width,
crop: type.crop,
upscale : false
}
// only specify the height if it exists
if (type.hasOwnProperty("height")) {
resize_settings.height = type.height
}
var rename_settings = {}
var dowatermark = type.watermark;
if(type.hasOwnProperty("prefix")) {
rename_settings.prefix = type.prefix
}
if(type.hasOwnProperty("suffix")) {
rename_settings.suffix = type.suffix
}
gulp
// grab all images from the folder
.src(paths.src)
.pipe(gulpif(dowatermark, watermark({
image: 'watermark.png'
})))
// resize them according to the width/height settings
.pipe(imageresize(resize_settings))
// optimize the images
.pipe(imagemin({
progressive: true,
// set this if you are using svg images
svgoPlugins: [{removeViewBox: false}]
}))
.pipe(rename(rename_settings))
// output each image to the dest path
// maintaining the folder structure
.pipe(gulp.dest(paths.dest+type.folder));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment