如何使用 grunt 将不同的图像调整为不同的大小?

How to resize different images into different sizes using grunt?

我有一个文件夹,里面有 20 多张图片。我想使用 grunt 调整所有图像的大小,每个图像都有不同的尺寸来调整大小。搜索后我遇到了 grunt image-resize 可以解决我的问题。

grunt.initConfig({
   image_resize: {
      resize: {
         options: {
            width: 100
         },
         files: {
            // list of files
         }
      }
  }
})

但是如何为每个图像指定尺寸?

G运行t 插件的一个不错的特点是大多数都是 Multi Tasks。什么是多任务?它们允许您使用不同的配置来执行插件。最重要的是,如果您不指定要使用的配置,插件将遍历所有配置。这意味着您可以为 a.jpg 指定一个配置,为 b.jpg 指定一个配置,依此类推。

现在,有两种方法可以做到这一点。您可以对各个配置进行硬编码,也可以即时动态生成配置。

硬编码配置

第一个选项是创建不同的个人配置:

grunt.initConfig({
   image_resize: {
      "a.jpg": {
         options: {
            width: 100,
            height: 100
         },
         files: {
            "foo/a.jpg": "foo/b.jpg"
         }
      },
      "b.jpg": {
         options: {
            width: 1600,
            height: 900
         },
         files: {
            "foo/b.jpg": "foo/b.jpg"
         }
      }
  }
})

等等。此时,您可以使用 grunt image_resize:a.jpg 运行 一次调整大小(如果您愿意),或者您可以 运行 使用 grunt image_resize 所有这些。这种方法适用于 20 张图像,但硬编码不是可扩展的解决方案;如果您计划随着时间的推移添加大量图像,您可能需要查看动态配置。

动态配置

对于那些对每个单独的配置进行硬编码过于繁琐的情况,您可以通过创建自定义任务来动态创建配置,首先创建配置,然后 运行 实际的图像调整任务。

在这种情况下,插件的配置如下所示:

grunt.initConfig({
   image_resize: {}
})

注意到没有配置了吗?这是因为在我们告诉 g运行t 到 运行 插件之前,自定义任务将用我们的动态配置替换那个空对象。

要动态创建我们的配置,我们的自定义任务需要:

  • 一个映射,告诉函数 width/height 用于哪个 文件
  • A globbing pattern 所以 G运行t 知道要查看哪些文件

一旦我们有了这两个,我们就可以创建我们的自定义任务:

function BatchImageResize() {
    var config = {},
        pattern = "path/to/**/*.jpg",
        mapping = {
            "a.jpg": {
                width: 100,
                height: 200
            },
            "b.jpg": {
                width: 1600,
                height: 900
            }
        };

    //our grunt task iterates through the files
    //if a mapping exists for the file, it creates a config 
    grunt.file.expand(pattern).forEach(function (filePath) {
        var fileName = filePath.split('/').pop().split('.')[0];
        if (mapping[fileName]) {
            config[fileName] = {
                options: {
                    width: mapping[fileName].width,
                    height: mapping[fileName].height
                },
                files: {
                    ['path/foo/', fileName].join('') : ['path/bar', fileName].join('')
                }
            }
        }
    });

    // sets the configs we just dynamically created.
    // these configs only exist during runtime! 
    grunt.config('image_resize', config);

    //Now let's run the image resize task
    grunt.task.run(['image_resize']);
}

//Let's make our task accessible from the command line
grunt.registerTask('batch', BatchImageResize);

然后我们将 运行 我们的批次使用 grunt batch。该任务将 运行,为 image_reize 创建批处理配置,然后在最后启动该任务。值得注意的是:对于动态配置,如果我们尝试直接 运行 grunt image_resize ,它将失败,因为配置不存在。