用Ruby替换图像?

时间:2011-06-09 00:40:51

标签: ruby image

如果我的文件夹中包含数千个大小相同的图像,我可以拍摄1张图像并用Ruby替换所有其他图像(但保留文件名)吗? 如果是这样,你会怎么做呢?

1 个答案:

答案 0 :(得分:3)

首先,如果我理解你的问题,你希望这样做:

  1. 使用dog.jpg (image of a dog)cat.jpg (image of a cat)horse.jpg (image of a horse)
  2. 创建目录
  3. 选择dog.jpg作为源图像
  4. 在保留文件名的同时用狗替换​​猫和马的图像
  5. 导致目录中包含dog.jpg (image of a dog)cat.jpg (image of a dog)horse.jpg (image of a dog)
  6. 你可以使用这样的函数,

    require 'FileUtils'
    
    def operate_on_directory(source_image, extensions)
      Dir.glob("*.{#{extensions.join(',')}}") do |file|
        FileUtils.cp(source_image, file) unless file == source_image
      end
    end
    
    operate_on_directory("dog.jpg", ["jpg", "png"])