Creating image collage using rmagick on rails.

In one of the my rails project project, I came across the problem of making collage of many images. I fought for it, with google as companion, still it took a whole day of searching to find good tool to do this.

Initially my approach was to use Rmagick – montage command. But montage takes array of image addresses and embeds them one after another to create a collage. One can give height and width for collage size or no. of images as heightwise and widthwise.  But in my collage there were going to be some images which were more in height than others. With montage, this image with more height was problem, as it increases height of the row it exists and causes blank space to remain below short height images.

So, to create a collage of images, i was looking for something which will allow to give list of images as well as co-ordinates to place those images. Finally i found that kinda functionality with composite command of Rmagick. This solved all of my problems.

The application was, user will be able to create designed images, with use of different images dragged and dropped from shelf. I needed to create a collage by taking co-ordinates of dropped images and there paths. Here is the code of it, which i wrote i model, i.e. before saving order, i used to create collage of images.-

require 'RMagick'
include Magick

class Order < ActiveRecord::Base

def drowit(tiles, board_details, size)

    cat = Image.new(size[:width].to_i, size[:height].to_i)
    logger.info(tiles.count)

    tiles.each_with_index do |t, i|
      tileimage = ImageList.new("#{RAILS_ROOT}/public#{t.photo.url}")
      cat.composite!(tileimage, board_details[i][3].to_i, board_details[i][2].to_i, OverCompositeOp)
    end

    file_path = "#{RAILS_ROOT}/public/order/mo_#{self.id}.jpg"
    cat.write(file_path)
    self.file_path = "/public/order/mo_#{self.id}.jpg"
  end

end

In above code, tiles was array of images(Tile was a active record model), board_details was again a array with image co-ordinates stored in it and size was Hash with collage height and width specified inside it.

In short to summarize, above code can given as –

cat = Image.new(HeightInPX, WidhtInPX)
tileimages = ImageList(PathOfImageToBeAdded)
cat.composite!(tileimage, LeftCo-ordinate, TopCo-ordinate, OverCompositeOp)
cat.write(FileNameAndPathToStoreNewImage)

Refrences –

Composite Refrences – http://rmagick.rubyforge.org/src_over.html

Montage References – http://www.imagemagick.org/RMagick/doc/optequiv.html#montage

  • http://twitter.com/#!/aseaofsins toasty redhead

    Thank you for a great post.

Email