GreenShoes を使って画像ファイルの変換 GUI を作ってみる
Ruby の GUI ツールである GreenShoes を使ってみました。
Linux mint 17.2 で確認しました。ImageMagick のインストールが必要です(Gem 'RMagick' は必要ありません)。
$ sudo apt-get install imagemagick
GreenShoes についてはこちらも。
単独のファイル変換と、フォルダの中の特定の画像形式のファイルを一括変換('converted' フォルダを作ってその中に出力します)する機能を付けました。
require 'bundler/setup' require 'green_shoes' Suffix = %w(png PNG jpg jpeg JPG JPEG gif GIF bmp BMP) class String def imgfile? return false unless m = /\.(.+)$/.match(self) return m[1] if Suffix.include?(m[1]) false end def imgsuffix Suffix.each do |sf| a = "." + sf return a if include?(a) end "" end end Shoes.app width: 500, height: 480 do background lavender title "画像変換" fname1 = fname2 = "" stack height: 120 do background azure b = button "変換されるファイルを選択" do fname1 = ask_open_file end a = para "" b.click {a.clear; a = para fname1} end para "変換先のファイル名" edit_line(width: 300) {|e| fname2 = e.text} button "変換" do if fname1.imgfile? and fname2.imgfile? Dir.chdir(File.dirname(fname1)) `convert #{fname1} #{fname2}` puts "converted" exit end end fname3 = "" sf1 = sf2 = "" para "\n" stack height: 120 do background moccasin para "一括変換するフォルダ" b = button "選択" do fname3 = ask_open_folder end a = para "" b.click {a.clear; a = para fname3} end para "画像形式を選択して下さい(変換前/変換後)" list_box items: ["jpg", "png", "bmp", "gif"] {|t| sf1 = t.text} list_box items: ["jpg", "png", "bmp", "gif"] {|t| sf2 = t.text} button "変換" do if sf1 != sf2 Dir.chdir(fname3) unless File.exist?("converted") and File.directory?("converted") Dir.mkdir("converted") end Dir.glob("*").each do |fn1| a = fn1.imgsuffix.downcase a = ".jpg" if a == ".jpeg" if File.file?(fn1) and a == "." + sf1 fn2 = /(.+)\..+$/.match(fn1)[1] + "." + sf2 `convert #{fn1} ./converted/#{fn2}` end end puts "converted" exit end end end
こんな感じ。
まあ自分のはあんまりカッコいいデザインではないのですが、GreenShoes を使うのはとにかく簡単です。どんどん GUI が作れそう。
Windows
Windows でも可能です(Windows 8.1 で確認)。ImageMagick と Gem 'GreenShoes' をインストールして下さい。
上のコードそのままでは動きません。まず、エンコードの関係で、文字列リテラルにすべて .encode("utf-8")
を付加します。
それから、驚いたことに Ruby の Bug(参照)というのが出ます。それを避けるコードにするために、多少の改変が必要です。具体的には、`convert #{fname1} #{fname2}`
のところで「バグ」が出ます。