I have Image
model and Movie
model and Movie
can have many images
. I am storing 3 versions of an image, big, medium and small
.
In my app users can pick images of a particular size lets say 4 images of `medium' size and then user can share them. Minimum 3 images and maximum 5.
I need to create a image with all selected 4 images of medium size. I do not want to send these images individually, I want to send it as a single image.
I am using Carrierwave
and MiniMagick
.
Thanks for help!
Assuming the real question here is about compositing images with minimagick, here's some code. Note that I've added a field to Movie called "composite_image", and I've decided that the uploader attached to Image is named "file".
def render_composite_image(source_images, coordinates)
temp_file = TempFile.new(['render_composite_image', '.jpg'])
img = MiniMagick::Image.new(temp_file.path)
img.run_command(:convert, "-size", "#{ COMPOSITE_WIDTH }x#{ COMPOSITE_HEIGHT }", "xc:white", img.path)
source_images.each_with_index do |source_image, i|
resource = MiniMagick::Image.open(source_image.file.path)
img = img.composite(resource) do |composite|
composite.geometry "#{ coordinates[i].x }x#{ coordinates[i].y }"
end
end
img.write(temp_file.path)
self.update_attributes(composite_image: temp_file)
end
A couple notes on this code:
source_images
is an array of images you want to composite together.
coordinates
is an array of coordinate values for where you want each image to be in the final composition. A coordinate's index corresponds to the respective source_image's index. Also note that if a coordinate is positive, you need to include a "+" character, e.g. "+50". (You may need to experiment to find the coordinates you want.)
If your images aren't stored locally, you'll need to use source_image.file.url
instead of source_image.file.path
.
This code was written to run in the context of a Movie model, but it could be moved wherever you like.