Image format gotcha

I’ve been doing a lot of testing witn RMagick lately, in view of reports
that it leaks memory. I’m happy to report that RMagick doesn’t seem to
leak at all, when used as directed – that is, when you remember to set
the image variable to nil and call GC.start manually after you’re done
with an image.

BUT – one ImageMagick format seems to be leaky! I was using the native
“MPC” format to store an intermediate image for processing, since
(according to the ImageMagick docs) it maps directly into memory and
should be very quick-loading. I kept seeing big increases in
virtual-memory allocation every time I used that image. The problem went
away when I changed the format of the intermediate file to anything else
(PNG, JPG).

Here’s the quickie script I sent to Timothy H. demonstrating the
problem. I’ve only tested it on a Mac (OS 10.4.6), so it might be
OS-specific. You might have to change the ps command – what you’re
interested in is virtual memory allocation.

–Al Evans


#!/usr/bin/env ruby

require ‘RMagick’
include Magick

name of original photo without extension

def photo_basename(name)
name.gsub(/.\w+$/i, ‘’)
end

def make_image_cache(pic_file_name)
img = Image.read(pic_file_name).first
img.strip!.change_geometry(“1024x1024”) { |cols, rows, img|
img.resize!(cols, rows)
}
img.write("#{photo_basename(pic_file_name)}.MPC")
img = nil
GC.start
end

def make_image_workfile(pic_file_name)
img = Image.read("#{photo_basename(pic_file_name)}.MPC").first
img.strip!.change_geometry(“640x512”) { |cols, rows, img|
img.resize!(cols, rows)
}
img.write("#{photo_basename(pic_file_name)}_work.JPG") { self.quality
= 50 }
img = nil
GC.start
end

while true
make_image_cache(ARGV[0])
make_image_workfile(ARGV[0])
puts ps -l | grep ruby
sleep(10)
end