neverbendeasy
neverbendeasy

Reputation: 988

How do I append dynamic text to image using rmagick?

I'm building a rails app where a user can type in six words about themselves and upload an image. I want to append those six words to the image.

I know how to get text append to work using "static" text, but I don't know how to link the text field to the form the users fill out when they type in their six words.

Right now, 'Text' is static and whatever I put.

I wonder why the following doesn't 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 become a little less of a n00b! :)

Upvotes: 4

Views: 1735

Answers (1)

neverbendeasy
neverbendeasy

Reputation: 988

Figured it out with the help of a friend.

This is all that 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 the variable that points to whatever instance object the uploader is attached to. In my model, name was the name of the form field that took the user text input.

For other use cases you'd just take model.field_name where you put whatever name you give to your field_name.

My friend wrote it like this to explain it to me. I'm pasting it here in case it can help others.

The 'process' method in ImageUploader is a static class method which only gets called once when the file is loaded into memory and interpreted by ruby. It's basically just internally keeping track of which processing methods should be called later on for every instance of ImageUploader. The textify method is the instance method that gets called on each ImageUploader object instance that gets created. The 'mount_uploader' class method that you call in your Athlete model is doing some ruby magic to instantiate the ImageUploader instance and pass your athlete instance object to it, making it available to the ImageUploader object instance as an instance method called 'model'.

Upvotes: 4

Related Questions