Exposing image geometry for <img> tags

45 views
Skip to first unread message

Nick

unread,
Feb 3, 2010, 9:16:39 PM2/3/10
to Paperclip Plugin
First off, thanks for such an awesome plugin. I've used it in a
couple projects and am very happy with it.

In order to write an <img> tag with width and height attributes, I
needed to get the geometry of an image that had been resized and
stored by Paperclip. Here's how I accomplished this, in case it helps
anyone with the same need, or in case anyone has a better way of doing
it.

(I wanted this because my app has the potential to show lots of large
images on a single page, and adding the image size to all the <img>
tags greatly reduces browser reflows.)

# get a Paperclip::Geometry object
geometry = Paperclip::Geometry.from_file(@user.avatar.path(:large))

# get the size in a format the image_tag helper can use
size = geometry ? geometry.to_s : nil

# use the size
<%= image_tag @user.avatar.url(:large), :size => size %>

I have a couple of suggestions, in case nothing like this is done yet:

First, it would be useful to be able to call
@user.avatar.geometry(:large) directly without having to go through
Paperclip::Geometry.from_file.

Second, it might be good to cache the geometry values when the
thumbnails are first created by Paperclip. Since the number of styles
isn't known at design time, it might make sense to have an
<attachment>_geometry field that stores a YAML-encoded hash of the
styles and the associated image sizes. As with some of the others,
this could be an optional field that is ignored when not present.

Anyway, what I have right now works, but I thought I'd throw a couple
ideas out there. Hopefully this can help someone else as well.

Nick

Kennon Ballou

unread,
Feb 4, 2010, 11:25:02 AM2/4/10
to papercli...@googlegroups.com
My fork of paperclip (http://github.com/kennon/paperclip) does exactly
that (caches the geometry in the DB); Jonathan has said that he doesn't
want to merge this (or things like it) into master because he feels that
it's too image-centric for paperclip (which I can understand, but there
are already image-centric things like :style support, but oh well :-)

Anyway, check it out, see if it does what you need it to. I've been
trying to keep it synced with master fairly well, although it's a couple
months out of date now and I'll try to update it soon.

| Kennon Ballou
| Angry Turnip, Inc.

Nick Pearson

unread,
Feb 4, 2010, 11:38:18 AM2/4/10
to papercli...@googlegroups.com
Excellent, thanks!  I'll have a look and may consider switching, or at least using your fork for new apps.  It's not as much of a concern for my current app (a CMS) because it makes extremely heavy use of page caching.  Nonetheless, I think this is a very useful feature, especially when performance is important.

Nick
Reply all
Reply to author
Forward
0 new messages