Skip to content

Instantly share code, notes, and snippets.

@higuma
Created September 12, 2016 11:08
Show Gist options
  • Save higuma/81dce73b7dea5e5f8417980778097276 to your computer and use it in GitHub Desktop.
Save higuma/81dce73b7dea5e5f8417980778097276 to your computer and use it in GitHub Desktop.
Convert multi-format images to JPG (using ImageMagick on ruby)
#!/usr/bin/env ruby
# Convert non-destructive format(PNG/BMP/TIFF) images to JPEG
# (for Windows, runs on git bash only)
#
# Requires ImageMagick: set correct ImageMagick path as below
# (e.g. convert.exe collides with Windows system command)
IM_PATH = 'C:/usr/ImageMagick'
IM_CONVERT = "#{IM_PATH}/convert"
require 'find'
require 'pathname'
require 'fileutils'
# puts + flush (required to display progress: git bash has big buffer!)
def puts(s) # overrides Kernel.puts
STDOUT.puts s
STDOUT.flush
end
exit_code = 0
Find.find(ARGV[0] ? ARGV[0].encode(Encoding::UTF_8) : '.') do |f|
src = Pathname.new f
next unless src.file?
ext = src.extname
next unless ['.PNG','.BMP','.TIF','.TIFF'].index ext.upcase
dst = src.dirname + "#{src.basename ext}.jpg"
if dst.exist?
puts "WARNING(#{ext} => .jpg): \"#{dst}\" already exists (skipped)"
exit_code = -2
else
if system "#{IM_CONVERT} \"#{src}\" \"#{dst}\""
puts "\"#{src}\" => .jpg"
FileUtils.rm src
else
puts "ERROR(#{ext} => .jpg): cannot generate \"#{dst}\""
exit_code = -1
end
end
end
exit exit_code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment