In this article, I am going to walk you through a simple technique for resizing images on the server in your Ruby On Rails app using MiniMagick. I have previously written about a technique for resizing images using javascript on the client, but I prefer the server method when possible.

MiniMagick is a ruby gem/plugin that is a wrapper around a great ruby image library called ImageMagick. There is also another well known library called RMagick that wraps ImageMagick that includes a lot more features. I chose MiniMagick for my case since I am on a shared host and the memory footprint is much smaller for MiniMagick since it basically just wraps the ImageMagick command line utilities.

Prerequisites

So, before we get started, make sure you have ImageMagick installed on your machine.

MiniMagick comes as both a gem and a plugin. Choose the one that makes sense for your project and install it. In my case, I chose the plugin since I wanted to keep MiniMagick checked in with my code in subversion.

To install the MiniMagick plugin, just download the plugin zip and extract it into your vendor/plugins directory. Please read up on the NOTES at the bottom of this article before you go for a few bugs I found with the plugin and how to fix them.

Usage

In my case, I decided to create a separate Image model for managing my images. In my Image model, I added this resize method:

def self.resize(path)
  image = MiniMagick::Image.new(path)
  w, h = image['%w %h'].split
  w = w.to_f
  h = h.to_f
  @@max_size = 100
  if (w > @@max_size || h > @@max_size)
    if (w > h)
      h = (h*(@@max_size/w)).to_i
      w = @@max_size
    else
      w = (w*(@@max_size/h)).to_i
      h = @@max_size
    end
    image.thumbnail "#{w}x#{h}"
  end
end

Now, let’s break down some of the more interesting parts:

image = MiniMagick::Image.new(path)

The above line is used to create a new MiniMagick Image object. By using the new method, I will be manipulating the actual image file on disk rather than working on a copy. If you wanted to work on a copy without modifying the original image you could the MiniMagick::Image.from_file(path) instead. When working on a copy, you would also have to use the MiniMagick::Image.write(path) method to save your image after the manipulations.

w, h = image['%w %h'].split

This line is used to grab the image width and height. The array ([]) syntax of the MiniMagick::Image class is really just a wrapper around the identify utility in ImageMagick. For a full list of options, refer to this documentation.

The remainder of that method up until the line below is just an algorithm for resizing the image to no larger than 100px on its largest side. It maintains the aspect ratio as well.

image.thumbnail "#{w}x#{h}"

The line is used to actually resize the image based on our new computed width and height. The MiniMagick::Image library exposes all of the options provided by the ImageMagick mogrify utility. For a full list of options for mogrify refer to this documentation. If you chose to create your image using the MiniMagick::Image.from_file(path) method, here is where you would write your image back to disk.

And that’s it! You should be happily resizing images using MiniMagick in no time.

NOTES: At the time of this posting, the MiniMagick plugin had a few bugs, which I have logged:

  1. In the init.rb, change this line:
    require 'mini-magic'
    

    to:

    require 'mini_magic'
    
  2. If you are using the MiniMagick::Image.write method, you will need to add the “rb” (read binary) option to the open statement within it. The final write method should read as follows:
    def write(output_path)
      open(output_path, "wb") do |output_file|
        open(@path, "rb") do |image_file|
          output_file.write(image_file.read)
        end
      end
    end
    

A New Gift Hat Release

July 17th, 2006

I just released a new version of the GiftHat.com.

This release includes a ton of new things including:

  • A total redesign of the look and feel
  • An all new friends feature for linking up with your friends at the GiftHat.com
  • Improved gift browsing including popular and recent gifts
  • Improved tagging support including tag lists and tag clouds
  • Support for username based Gift Hat URLs, such as:
    http://gifthat.com/atomgiant
  • An improved bookmarklet to pave the way for better Gift Hat bookmarks in the future.
  • Locally stored gift thumbnails.
  • Stop by and check it out if you have a few minutes.

If you ever need to count your Rails records based on a distinct column, here is a simple solution:

Gift.count_by_sql("select count(distinct url) from gifts")

In this example, I am counting the number of distinct gift urls from my gifts table.

It has been rather quiet around here as I have been rather busy lately trying to get the next release of the GiftHat.com out the door.

In the meantime, here is a simple technique I like to use to focus a form on a web page using Prototype’s built in Events:

The solution

For those of you who just want to dive right in, here is the solution:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <script src="/javascripts/prototype.js" type="text/javascript"></script>
</head>
<body>

    <script type="text/javascript">
//<![CDATA[
Event.observe(window, 'load', function() {$('focus').focus()}, false);
//]]>
</script>
<form action="/login" method="post" name="loginForm">
  <label for="username">Username</label><br/>
  <input id="focus" name="user[username]" size="30" tabindex="1" type="text" />
  <label for="username">Username</label><br/>
  <input name="user[password]" size="30" tabindex="1" type="password" />
  <input name="commit" tabindex="3" type="submit" value="Submit" />
</form>
</body>

</html>

The explaination

This line requires the prototype library:

<script src="/javascripts/prototype.js" type="text/javascript"></script>

The Event.observe javascript is where the magic happens:

<script type="text/javascript">
//<![CDATA[
Event.observe(window, 'load', function() {$('focus').focus()}, false);
//]]>
</script>

This will setup an event that will cause our dynamic function to be called when the window loads. This function will lookup an element that has an ID called focus and call its focus() method.
In case you are wondering what the CDATA part is for, that will just make sure this webpage still validates.

The last part of this is to create an element that has an ID of focus which will get the browser focus after the window loads. In the example above, it is this form element that gets the focus:

<input id="focus" name="user[username]" size="30" tabindex="1" type="text" />

You can definitely do a lot more interesting things with Prototype events than this example, but this should help get the ball rolling.