Ruby on Rails
HowtoCreateThumbnailImages (Version #35)

You can create thumbnails by creating simple script either using GD library or ImageMagick.

Here is simple script which is ideal to use in your Ruby on Rails application to quickly generate thumbnails of any proportions. It uses GD graphic library. Just set width and height and get the image. You can create thumbnails by calling image URL with width and height as parameters e.g. /thumb/photo.jpg?w=400&h=350 and you will see resized picture “photo.jpg”. Ideal for displaying multiple images or photo thumbnails in photo gallery. Just run it inside a loop.

Download Ruby on Rails thumbnail generator

Installation is easy as three simple steps:

1. copy downloaded controller into /controllers/thumb_controller.rb

2. edit /config/routes.rb and add this line:
map.connect “thumb/*specs”, :controller => “thumb”, :action => “index”

3. create directory /imagelib/ in RoR’s /public/ directory and
/image_cache/ inside /imagelib/ directoory

photo.jpg should be stored in /public/imagelib/ directory. Off course you can change directory structure if you wish just don’t forget to edit thumb_controller.rb than.

This is very simple solution, it stores picture on disk and also stores resized picture on disk a a cache.

Here is another method:

%{color:red;}*Note:* This method involves storing both the uploaded image and its respective thumbnail in a database. This is not an ideal method, since MySQL has default variables which won’t allow you to upload files of any more than about 100kb. I haven’t got time for a re-write now, but try and adapt it to store in the filesystem. %

Note: The attachment_fu plugin by Rick Olson makes this process easier, has the ability to store in the filesystem or database, and integrates with Amazon S3.

This page deals with how to create thumbnail images from an image uploaded through an HTML form.

We’ll assume the controller is named ‘app’ and the action with the upload form is named ‘files’. The form data will be sent to an action called ‘upload’.

Important: This tutorial requires that you have Mini-Magick plugin installed. You can install this via a gem, but first you will need to (if you have not already) run the following command at the command-line: gem install hoe --include-dependencies. Then, you can download the mini-magick gem from Ruby Forge and [supposed you stored the .gem file in C:], run the following command at the command-line: gem install C:/mini-magick.gem.

Let’s start with the form code in the view:

<form action="/app/upload" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload a file


label for="upload_file">File:


<%= "upload", "tmp_file" %>
<%= submit_tag "Upload file" %>


Now, let’s create the action for dealing with the uploaded file. We’ll be storing both the file and the generated thumbnail in a database table named ‘Uploads’, with BLOB fields named ‘data’ and ‘thumbnail’, a VARCHAR field named ‘filename’, and another VARCHAR field named ’contenttype’._

You will need to have required ftools at the beginning of your controller with your files and upload actions:

require 'mini_magick'
require 'ftools'

class AppController < ApplicationController
...


def upload
@file = Upload.new
@file.filename = params['upload']['tmp_file'].original_filename.gsub(/[^A-Za-z0-9\.]/,"_")
# Let's use the MIME type to check if the file is an image
@file.content_type = params['upload']['tmp_file'].content_type.chomp
if @file.content_type[-3,3] == "jpeg"||"/png"||"-png"||"gif"
image = MiniMagick::Image.from_file(params['upload']['tmp_file'].path)
# We'll resize the image to 200x140 pixels.
image.resize "200X140"
# We'll create a *temporary* thumbnail in a folder named 'thumbnails' within the 'tmp' folder in the application's root.
thumbnail = File.open("#{RAILS_ROOT}/tmp/thumbnails/thumb_"+rand(10000).to_s+".tmp","wb+")
image.write thumbnail.path
# Store the thumbnail in the database
@file.thumbnail = thumbnail.read
# Close the temporary thumbnail, then delete it
thumbnail.close
File.delete(thumbnail.path)
params['upload'].delete('tmp_file')
end
if @file.save
flash['notice'] = "The file has been uploaded"
redirect_to :action => "files"
end
end

So that’s it. Let’s now just go back over what this code does:

  1. It allows a user to upload a file which may or may not be an image.
  2. It stores the file in the database, and, if it’s an image, creates a thumbnail, by:
    1. Generating a temporary thumbnail.
    2. Storing the temporary file in the database.
    3. Deleting the temporary file from the file system.
  3. After creating (or not) the thumbnail, it completes the saving in the database, and re-directs to the original files view with a message stored in the flash.

But just a second, we’ve missed out the most important part — displaying the thumbnail. This can be accomplished relatively easily used a two-line action named ‘thumbnail’.

def Thumbnail
@file = Upload.find(:first, :conditions => ["filename = ?", params['filename']], :select => "id, filename, thumbnail")
send_data @file.thumbnail, :filename => @file.filename, :type => @file.filetype, :disposition => "inline"
end

This action does two things:

  1. First, it retrieves the file row from the database.
  2. Second, it outputs the thumbnail image.

To display this in the view, simply use this image tag: <img src="/app/thumbnail?filename=<%=h file.filename %>" alt="" />, where ‘file.filename’ refers to the database row and its field filename. The best way to display all images is to loop through all the files in the database, display the filename, and, if there is a thumbnail, display it.

You can create thumbnails by creating simple script either using GD library or ImageMagick.

Here is simple script which is ideal to use in your Ruby on Rails application to quickly generate thumbnails of any proportions. It uses GD graphic library. Just set width and height and get the image. You can create thumbnails by calling image URL with width and height as parameters e.g. /thumb/photo.jpg?w=400&h=350 and you will see resized picture “photo.jpg”. Ideal for displaying multiple images or photo thumbnails in photo gallery. Just run it inside a loop.

Download Ruby on Rails thumbnail generator

Installation is easy as three simple steps:

1. copy downloaded controller into /controllers/thumb_controller.rb

2. edit /config/routes.rb and add this line:
map.connect “thumb/*specs”, :controller => “thumb”, :action => “index”

3. create directory /imagelib/ in RoR’s /public/ directory and
/image_cache/ inside /imagelib/ directoory

photo.jpg should be stored in /public/imagelib/ directory. Off course you can change directory structure if you wish just don’t forget to edit thumb_controller.rb than.

This is very simple solution, it stores picture on disk and also stores resized picture on disk a a cache.

Here is another method:

%{color:red;}*Note:* This method involves storing both the uploaded image and its respective thumbnail in a database. This is not an ideal method, since MySQL has default variables which won’t allow you to upload files of any more than about 100kb. I haven’t got time for a re-write now, but try and adapt it to store in the filesystem. %

Note: The attachment_fu plugin by Rick Olson makes this process easier, has the ability to store in the filesystem or database, and integrates with Amazon S3.

This page deals with how to create thumbnail images from an image uploaded through an HTML form.

We’ll assume the controller is named ‘app’ and the action with the upload form is named ‘files’. The form data will be sent to an action called ‘upload’.

Important: This tutorial requires that you have Mini-Magick plugin installed. You can install this via a gem, but first you will need to (if you have not already) run the following command at the command-line: gem install hoe --include-dependencies. Then, you can download the mini-magick gem from Ruby Forge and [supposed you stored the .gem file in C:], run the following command at the command-line: gem install C:/mini-magick.gem.

Let’s start with the form code in the view:

<form action="/app/upload" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload a file


label for="upload_file">File:


<%= "upload", "tmp_file" %>
<%= submit_tag "Upload file" %>


Now, let’s create the action for dealing with the uploaded file. We’ll be storing both the file and the generated thumbnail in a database table named ‘Uploads’, with BLOB fields named ‘data’ and ‘thumbnail’, a VARCHAR field named ‘filename’, and another VARCHAR field named ’contenttype’._

You will need to have required ftools at the beginning of your controller with your files and upload actions:

require 'mini_magick'
require 'ftools'

class AppController < ApplicationController
...


def upload
@file = Upload.new
@file.filename = params['upload']['tmp_file'].original_filename.gsub(/[^A-Za-z0-9\.]/,"_")
# Let's use the MIME type to check if the file is an image
@file.content_type = params['upload']['tmp_file'].content_type.chomp
if @file.content_type[-3,3] == "jpeg"||"/png"||"-png"||"gif"
image = MiniMagick::Image.from_file(params['upload']['tmp_file'].path)
# We'll resize the image to 200x140 pixels.
image.resize "200X140"
# We'll create a *temporary* thumbnail in a folder named 'thumbnails' within the 'tmp' folder in the application's root.
thumbnail = File.open("#{RAILS_ROOT}/tmp/thumbnails/thumb_"+rand(10000).to_s+".tmp","wb+")
image.write thumbnail.path
# Store the thumbnail in the database
@file.thumbnail = thumbnail.read
# Close the temporary thumbnail, then delete it
thumbnail.close
File.delete(thumbnail.path)
params['upload'].delete('tmp_file')
end
if @file.save
flash['notice'] = "The file has been uploaded"
redirect_to :action => "files"
end
end

So that’s it. Let’s now just go back over what this code does:

  1. It allows a user to upload a file which may or may not be an image.
  2. It stores the file in the database, and, if it’s an image, creates a thumbnail, by:
    1. Generating a temporary thumbnail.
    2. Storing the temporary file in the database.
    3. Deleting the temporary file from the file system.
  3. After creating (or not) the thumbnail, it completes the saving in the database, and re-directs to the original files view with a message stored in the flash.

But just a second, we’ve missed out the most important part — displaying the thumbnail. This can be accomplished relatively easily used a two-line action named ‘thumbnail’.

def Thumbnail
@file = Upload.find(:first, :conditions => ["filename = ?", params['filename']], :select => "id, filename, thumbnail")
send_data @file.thumbnail, :filename => @file.filename, :type => @file.filetype, :disposition => "inline"
end

This action does two things:

  1. First, it retrieves the file row from the database.
  2. Second, it outputs the thumbnail image.

To display this in the view, simply use this image tag: <img src="/app/thumbnail?filename=<%=h file.filename %>" alt="" />, where ‘file.filename’ refers to the database row and its field filename. The best way to display all images is to loop through all the files in the database, display the filename, and, if there is a thumbnail, display it.