首页 > 解决方案 > 使用 Gulp 从数组中批量重命名图像

问题描述

我想使用 Gulp 批量调整和重命名图像。我有一项任务是根据文件的尺寸重命名文件,但我想在文件名中使用简写,比如-smalland-large并且只使用数值来调整大小的过程。

我尝试将键:值对数组的一些迭代添加到该.forEach行...

[small:100, large:1000].forEach(function (size) [{small:100, large:1000}].forEach(function (size)

...然后尝试定位图像imageResize行中的键/值,其中“k”将是键。这对我不起作用,到目前为止我还没有成功地跟踪这部分。

.pipe(rename(function (path) { path.basename = `${path.basename}-${size[k]}px`; }))

这是当前任务,它完成了工作。它基于 调整图像大小size,然后size作为字符串附加到文件名。

// Optimize Images
gulp.task("images", function (done) {
  [100, 1000].forEach(function (size) {
    return gulp.src(imagesSRC)
    .pipe(newer(imagesDestSite)) // get newer images
    .pipe(imageResize({ width: size })) // resize each according to array above
    .pipe(rename(function (path) { path.basename = `${path.basename}-${size}px`; })) // put size in filename
    .pipe(imagemin())
    .pipe(gulp.dest(imagesDest))
    .pipe(browserSync.reload({stream:true}))
    .pipe(gulp.dest(imagesDestSite))
  });
  done();
});

该任务的输出当前如下所示:

image1-100px.jpg image1-1000px.jpg image2-100px.jpg image2-1000px.jpg

哪个有效,但我希望输出是这样的:

image1-small.jpg image1-large.jpg image2-small.jpg image2-large.jpg

任何指针将不胜感激,并在此先感谢!

标签: javascriptimageoptimizationgulprename

解决方案


推荐阅读