使用 gulp 重命名文件并添加索引

Renaming a file with gulp rename and adding an index

我需要重命名一批照片并为其添加索引,例如 'image-1-tmb' 或 'image-23-tmb'。这个我已经找过了,没找到,差点就找到了。

这是我的实际代码:

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'));
});

使用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...)

我想附加原始图像的大小... 就我而言,这是 a requirement of photoswipe.

尝试用 gulp 来做,不幸的是,即使在尝试附加当前图像的大小时我也卡住了:

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(...));