Ruby で画像を半分に分割

横に長い画像を半分に分割したかったので Rubymini_magick を使って書いてみた。

require "mini_magick"

def cut_image src
    left = MiniMagick::Image.open src
    return left, nil if left[:width] < left[:height]
    width = left[:width] / 2
    right = MiniMagick::Image.open src
    [
        left.crop("#{width}x#{left[:height]}+0+0"),
        right.crop("#{width}x#{left[:height]}+#{width}+0")
    ]
end


def save_cut_image src, out = "./"
    FileUtils.mkdir out unless Dir.exist? out

    fname = File.basename src, ".png"
    p "#{out}/#{fname}_A.png"

    left, right = cut_image src
    if right
        right.write "#{out}/#{fname}_A.png"
        left.write "#{out}/#{fname}_B.png"
    else
        left.write "#{out}/#{fname}.png"
    end
end

save_cut_image "image.png", "output"

捨てコードなので実装はだいぶ雑です。