Latest from the Bamboo Blog

IrregularScience martyn

February 19th, 2008

ImageScience is great. Just look at the code! One beautiful class wraps up FreeImage with some jucy inline C. If you can install FreeImage then nothing can go wrong. Much better than a bazillion lines of RMagick (which sometimes still can't so what you need)!

Simplicity is great but unfortunately ImageScience has this infatuation with squares. I'll explain.

Image science has two low level methods which allow arbitrary cropping and resizing. They look like this:

image.with_crop(left, top, right, bottom)

image.resize(width, height)

However what you really want to do is usually a combination of cropping and resizing. ImageScience helpfully provides:

# Resizes to fit within a square
image.thumbnail(size)

# Resizes and crops to be exactly a square
image.cropped_thumbnail(size)

This is great until you need an avatar that's a fixed ... rectangle. Or an image that will fit exactly inside a ... rectangle.

In this case you need IrregularScience!

You'll get rectangular versions of thumbnail and cropped_thumbnail:

# Resizes to fit within a rectangle
image.resize_within(width, height)

# Resizes and crops to be exactly a rectangle
image.resize_exact(width, height)

I gave my methods slightly different names because I'm like that ;)

There's also the case where you want a exact height or an exact width regardless of the other dimension (ever seen facebook?). That turns out to be a really horrible hack with RMagick involving all sorts of squashing and stretching unless you go really low level. Just follow these incantations and know that no horrible hacks are going on:

image.resize_to_width(width)

image.resize_to_height(height)

To get started download irregular_science.rb and require it. Then adapt this example:

ImageScience.with_image(upload_path) do |image|
  self.thumbnails.each do |name, size|
    image.resize_exact(*size) do |img|
      img.save(attachment_path(name))
    end
  end
end

Enjoy!

P.S. This seems to be my first blog post here - so hi!

3 Responses to “IrregularScience”

  • Jarkko

    Howdy, Martyn! I’ve wondered where you’ve ended up. Good to see it’s a friendly place like NB (rather than a slave ship or something :-)

  • Darrin

    Hey Martyn,

    So you joined new bamboo eh…

    I don’t suppose you’ve had any luck compiling freeimage on Leopard from source have you?

    Cheers,

    D

  • David Berube

    Incidentally, this is also trivial to do with RMagick – simply pass a string like “320×240” and RMagick will correctly preserve the aspect ratio. You can also use a bang on a particular size – “320×240” – to tell RMagick that it should treat that as an exact size. Otherwise, it will make the image fit inside of the rectangle you specify without messing up the aspect ratio. (FWIW, my upcoming book – coauthored with Nick Plante – covers this in a sidebar.)

    Take it easy, David Berube

Sorry, comments are closed for this article.