2015-10-19 90 views
2

我需要重新命名一批添加索引的照片,比如'image-1-tmb'或'image-23-tmb'。我已经查过这个,没有找到它,甚至没有接近找到它。用gulp重命名并添加一个索引来重命名一个文件

这是我的实际代码:

gulp.task('rsz_tmb_menu',function(){ 
return gulp.src('./zips/**/*.{jpg,JPG}', { base: './zips' }) 
.pipe(imageResize({ 
    width : width_tmb_menu, 
    height : height_tmb_menu, 
    crop : true, 
    quality : 0.6, 
    imageMagick : true, 
    upscale : false 
})) 
.pipe(gulp.dest('./images/tmb_menu')); 
}); 

回答

1

使用gulp-rename

var rename = require("gulp-rename"); 

然后添加到您的管道: gulp.task( 'rsz_tmb_menu',函数(){

var index = 0; 

gulp.src('your_glob') 
    .pipe(your processing func) 
    .pipe(rename(function (path) { 
    path.basename += ("-" + index++); 
})) 
.pipe(...dst...) 
0

我想这样做,以追加原始图像的大小... 在我的情况下,这是a requirement of photoswipe

试图用一口做到这一点,不幸的是,我在尝试追加当前图像的大小,即使卡:

var sizeOf = require('image-size'); 

(...) 

.pipe(rename(function (path) { 
    var dimensions = sizeOf(path); 
    path.basename += ("-" + dimensions.width + "x" + dimensions.height); 
})) 

引发错误:

node_modules/image-size/lib/index.js:79 
throw new TypeError('invalid invocation'); 

回答我自己的问题,以帮助某人
基于http://www.pixeldonor.com/2014/feb/20/writing-tasks-gulpjs/

return gulp.src(...) 
.pipe(through.obj(function (chunk, enc, cb) { 
     dimensions = sizeOf(chunk.path); 
     extname = Path.extname(chunk.path); 
     dirname = Path.dirname(chunk.path); 
     basename = Path.basename(chunk.path, extname); 
     chunk.path = Path.join(dirname, basename + "-" + dimensions.width + "x" + dimensions.height + extname); 
     this.push(chunk); 
     cb(null, chunk); 
})) 
.pipe(imageResize({ 
     width : 600, 
     height : 600, 
     crop : true, 
     upscale : true 
})) 
.pipe(gulp.dest(...));