Search code examples
rubyimagemagickrmagick

RMagick - How to crop grid image into an array of images?


The following imageMagick command will crop a sprite image into several images divided equally:

convert image.png -crop 2x3-40-20@ +repage +adjoin tile-%d.jpg

Hot do I do this with Rmagick? But instead of creating multiple files i need to return an array of images.


Solution

  • Managed to get it done by croping each image at a time:

    def split_images
      #'image' is a ImageMagick Object
      width  = image.cols/number_cols
      height = image.rows/nubmer_rows
      images = []
      0.upto(number_rows-1) do |x|
        0.upto(number_cols-1) do |y|
          images << image.crop( Magick::NorthWestGravity, x*width, y*height, width, height, true)
        end
      end
    end