Jan 15, 2009

Shrink your Pictures

There may come a time when you copy your images off your digital camera and realize that they are at some ridiculous dimension like 2000x1700, which is not really a nice size to be emailing to your friends and family.
It might be ok if you just have one to send, but when you have like 30, it is not so easy.

So here's a little something to shrink them all:
Dir.mkdir "small" unless File.exists?("small")

Dir.foreach(".") do |file|
next if file !~ /\.(jpg|png)$/i

puts "Shrinking #{file}"
`convert #{file} -resize "300x300>" small/#{file}`
end
This shrinks all the jpgs and pngs in a folder to a maximum of 300x300 while maintaining the aspect ratio. If the image is smaller, then it is not resized. It dumps all the images in a folder called small.

Or if you don't like Ruby, here it is in bash:
mkdir small
for i in $(ls | egrep -i "\.(jpg|png)$"); do
echo "Shrinking " $i
convert $i -resize "300x300>" small/$i
done
Now you can send your pictures to all your friends! Note that in order to use these, you'll need ImageMagick installed. As for doing this in Windows, I have no idea. A good bet might be to use RMagick and then use rubyscript2exe to make it work.

UPDATE: Suppose there are also some pictures that you want to rotate too. Luckily for us, ImageMagick handles this too. Unfortunately I don't know bash well enough to update the bash one, but for Ruby:
Dir.mkdir "small" unless File.exists?("small")

Dir.foreach(".") do |file|
next if file !~ /\.(jpg|png)$/i

out_file = ""
commands = ""

if file =~ /^rotate(\d+)_/
commands += "-rotate \"#{$1}\" "
out_file = file[/_(.*)$/, 1]
end

puts "Shrinking #{file} to small/#{out_file}"
`convert #{file} -resize "300x300>" #{commands} small/#{out_file}`
end
Now if you prefix any files you want to rotate with "rotateX_", it will rotate your files clockwise by X degrees. I'd recommend using 90.
It's great with any file browser that shows the thumbnails of the image, so you can just look, rename (by pressing F2 in Nautilus) and go.

This is also pretty easy to add on to if you want to add more filters. ImageMagick has a lot of stuff it can do - you can even make things into polaroids if you want.

1 comment:

DrSkrud said...

I do this kind of stuff all the time with ImageMagick! It's so useful! :D