How to add dynamic text to an image using rmagick?

I am creating a rails application where a user can enter six words about himself and upload an image. I want to add these six words to the image.

I know how to make a text application work using “static” text, but I don’t know how to associate a text field with a form that users fill out when they type in their six words.

Right now, the “Text” is static and everything I put.

I wonder why the following does not work?

process :textify => <%= @user.sixwords %> 

Here is what I have:

 process :textify => 'Text' def textify(phrase) manipulate! do |img| img = img.sepiatone title = Magick::Draw.new title.annotate(img, 0,0,0,40, phrase) { self.font_family = 'Helvetica' self.fill = 'white' self.pointsize = 32 } img = img.write('newimg.gif') end end 

Thanks for helping me get a little smaller than n00b! :)

+4
source share
1 answer

I found out with the help of a friend.

This is all I needed to change:

 title.annotate(img, 0,0,0,40, model.name) { self.font_family = 'Helvetica' self.fill = 'white' self.pointsize = 32 } 

This works because Carrierwave uses model as a variable that points to any instance object to which the loader is attached. In my model, name was the name of the form field in which the custom text was entered.

For other use cases, you just take model.field_name where you put any name you give your field_name .

My friend wrote it to explain it to me. I insert him here if he can help others.

The "process" method in ImageUploader is a static class method that only receives a call once when the file is loaded into memory and interpreted by the ruby. It basically just keeps track of which processing methods should be called later for each instance of ImageUploader. The textify method is an instance method that receives a call to each instance of the ImageUploader object that is created. The mount_uploader class method that you invoke in your Athlete model, doing ruby ​​magic to create an ImageUploader instance and pass it the athlete instance object, making it available to the ImageUploader object object as an instance method called "model".

+4
source

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


All Articles