Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine images in Ruby

I have 4 square images, 1,2,3 and 4 each with 2048x2048px.

I need to combine those into a 4096x4096px image, like this:

 1 2
 3 4

Right now I am doing this manually with Gimp, but the amount processing is growing and I would like to implement an automated solution.

Is there an easy way to do this in Ruby? (Rails gem would be ok or any shell command that can be run from inside a Rails app)

like image 739
Eduard Avatar asked Jun 10 '15 08:06

Eduard


1 Answers

I marked the accepted answer because was the starting point for solving my problem. I will also post the complete working solution here:

require 'rmagick'
class Combiner
include Magick

  def self.combine
    #this will be the final image
    big_image = ImageList.new

    #this is an image containing first row of images
    first_row = ImageList.new
    #this is an image containing second row of images
    second_row = ImageList.new

    #adding images to the first row (Image.read returns an Array, this is why .first is needed)
    first_row.push(Image.read("1.png").first)
    first_row.push(Image.read("2.png").first)

    #adding first row to big image and specify that we want images in first row to be appended in a single image on the same row - argument false on append does that
    big_image.push (first_row.append(false))

    #same thing for second row
    second_row.push(Image.read("3.png").first)
    second_row.push(Image.read("4.jpg").first)
    big_image.push(second_row.append(false))

    #now we are saving the final image that is composed from 2 images by sepcify append with argument true meaning that each image will be on a separate row
    big_image.append(true).write("big_image.jpg")
  end
end
like image 112
Eduard Avatar answered Oct 10 '22 07:10

Eduard