How to make an image using multiple images using Carrierwave and MiniMagick

I have an Image model and a Movie model, and a Movie can have many images . I save 3 versions of the image, big, medium and small . In my application, users can select images of a certain size, say 4 images of the "medium" size, and then the user can separate them. Minimum 3 images and maximum 5.

I need to create an image with all 4 selected medium sized images. I do not want to send these images separately, I want to send it as one image.

I use Carrierwave and MiniMagick .

Thanks for the help!

+4
source share
1 answer

Assuming here the real question is about arranging images using minimagick, here is some code. Notice that I added a field to the Movie called "composite_image" and I decided that the loader attached to the image is called the "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 few notes on this code:

  • source_images is an array of images that you want to merge together.

  • coordinates is an array of coordinate values ​​where you want each image to be in the final composition. The coordinate index corresponds to the corresponding source_image index. Also note that if the coordinate is positive, you need to add a β€œ+” symbol, for example. "+50". (You may need to experiment to find the coordinates you need.)

  • If your images are not stored locally, you need to use source_image.file.url instead of source_image.file.path .

  • This code was written to run in the context of the Movie model, but it could be moved anywhere.

+3
source

Source: https://habr.com/ru/post/1493163/


All Articles