I do write about the most exciting things.
Right so – ImageScience is a neat little ruby library for working with images without going through the drama, memory leaks and general hassle of using the full fat ruby image library Rmagick.
Image Science comes with the ability to produce a square thumbnail and a relational thumbnail. It doesn’t, however, come with a nice way of generating a ‘best fit’ thumbnail that will maintain aspect ratio, guarantee size and look alright most of the time. To save you some time, dear reader, I’ve done the googling, the code borrowing and the cleanup and come up with this:
The following method will allow you to give a target width and a target height get yielded back a thumbnail suitable for most occasions.
class ImageScience
def cropped_thumb(target_width,target_height)
aspect = target_width.to_f / target_height.to_f
ih, iw = height, width
w, h = (ih * aspect), (iw / aspect)
w = [iw, w].min.to_i
h = [ih, h].min.to_i
self.with_crop( (iw-w)/2, (ih-h)/2, (iw+w)/2, (ih+h)/2) {|crop|
crop.resize(target_width, target_height){|thumb|
yield thumb
}
}
end
end
And it looks like:
