Creating PNG from Memory Pixel Buffers with RMagick

Martin Dittus · 2006-07-09 · code · write a comment

Just so I won't forget, and because it's useful to know.

require 'RMagick'

# generate rgb image buffer
pixeldata = []
14.times do |y|
	100.times do |x|
		pixeldata << 1.0 - (x/100.0 * y/14.0)
		pixeldata << (x/100.0 + y/14.0) / 2
		pixeldata << (x/100.0)
	end
end

# convert to PNG
image = Magick::Image.constitute(100, 14, 'RGB', pixeldata)
rawdata = image.to_blob() { self.format = 'PNG' }

# display
puts "Content-Type: image/png"
puts
puts rawdata

...or simply write to file.

Result: t.png

Any hints on more lightweight PNG writers? ImageMagick can be a pain to install. There are some neat tricks for image-builders on why's sparklines for minimalists page, but jzp's PNG code shown there is for a very specific image and visualization format, and I don't understand PNG enough to adapt it.

Update 2006-12-09: Olle Jonsson sends a link to png, a lightweight pure-Ruby PNG library by Ryan Davis. gem install png...


Next article:

Previous article:

Recent articles:

Comments

Comments are closed. You can contact me instead.