Skip to content
Squeegy edited this page Sep 12, 2010 · 10 revisions

To actually create a template to render the image we create a special view with a .flexi extension. This view template will pull out the master image for you, transform it as needed, and send it to the browser as binary data.

The filename of the template should look like this: app/views/controller_name/action_name.jpg.flexi, where action_name is the controller action that will render this view. The jpg tells the controller to render this view when the jpg format is asked for. The flexi tells Rails to render this view with the Fleximage template engine, rather than erb or builder or other template types.

The syntax of the view is pure ruby, but to process the image the view needs to call operate on the instance of your model. This lets Fleximage know which instance variable contains the image that needs to be processed and sent out.

Here is the view to render a Photo record at 320×240:

# app/views/photos/show.jpg.flexi
# Accessed via http://mysite.com/photos/123.jpg
@photo.operate do |image|
  image.resize '320x240'
end

Calling @photo.operate { |image| .. } prepares the model object for image processing and yields a an object image that will allow you to perform image transformations. The above example just resizes the image to 320×240, however many other Operators are included with Fleximage.

Here is a .flexi template that will do much more:

# app/views/show.jpg.flexi
@photo.operate do |image|
  image.resize '640x480', :crop => true
  image.image_overlay 'public/images/logo.png',
    :alignment => :bottom_right,
    :offset => '20x20'
  image.border :size => 10, :color => 'green'
  image.text 'I like Cheese'
  image.unsharp_mask  
  image.shadow
end

The above template will:

  • Resize the image to exactly 640×480, cropping off any extra.
  • Add a logo 20 pixels form the lower right corner
  • Add a green 10 pixel border
  • Write “I like Cheese” in the upper left corner
  • Sharpen the image
  • Add a black drop shadow on a white background

See the Operators page for a full inventory of all the operators included with Fleximage.

You can also use this syntax in the controller, which is useful when you’ve a lot of different formats to serve:


def thumb
  @photo = Photo.find(params[:id])
  render :inline => "@photo.operate {|p| p.resize '100x100'}", :type => :flexi
end

Conditional image inclusion

If you have a Fleximage model where an image is not mandatory (your model does not have require_image true) you may wish to adjust your view so that you render some alternate content if your model instance does not have an image. You can use the Fleximage::Model#has_image? to accomplish this. Here is an example:

<%  if @photo.has_image? %>
  <%= image_tag formatted_photos_path(@photo, :gif) %>
<% else %>
  <p>
    There is no image.
    <%= link_to 'Upload one now!', edit_photo_path(@photo) %>
  </p>
<% end %>
Clone this wiki locally