How to sort images into folders, based on resolution?

Background: I've got a folder full of saved desktop pictures. I'd like to put them into folders, based on their resolution - 1024x768, etc. Creating the folders on the fly is a bonus. Currently, the images are all in a folder, but some of them are in sub-folders. I can merge them by hand, if that makes things easier.

I'd prefer the terminal, though I'm still kind of a bash newbie. I'm not much of a programmer at all, really.

I'm using Mac OS X, but I'm not opposed to installing extra apps to accomplish this (MacPorts?), or even using another OS (I've got Windows XP, Windows Vista, and Ubuntu 9 setup right now within VMWare).


I know it's an over a year topic (sorry about that) but i think someone may need the full working script, so here it is. Taking the ideas here and compiling into a script we get.

#!/bin/bash

for image in *.jpg;
    do res=$(identify -format %wx%h\\n $image);
    mkdir -p $res;
    mv $image $res;
done

Seriously, thanks for replying, everyone! I've come back to this, more experienced, and most of the comments here make more sense now.

I tweaked @zatatlan's script slightly to accommodate spaces in filenames and to add more file extensions.

#!/bin/bash

shopt -s nullglob # The script spits errors if this is not set and there are, say, no *.png files.
for image in *.jpg *.JPG *.jpeg *.JPEG *.gif *.GIF *.bmp *.BMP *.png *.PNG;
    do res=$(identify -format %wx%h\\n "$image");
    mkdir -p $res;
    mv "$image" $res;
done