Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read an image pixel by pixel in Ruby

I'm trying to open an image file and store a list of pixels by color in a variable/array so I can output them one by one.

Image type: Could be BMP, JPG, GIF or PNG. Any of them is fine and only one needs to be supported. Color Output: RGB or Hex.

I've looked at a couple libraries (RMagick, Quick_Magick, Mini_Magick, etc) and they all seem like overkill. Heroku also has some sort of difficulties with ImageMagick and my tests don't run. My application is in Sinatra.

Any suggestions?

like image 929
Anders H Avatar asked Dec 03 '10 03:12

Anders H


2 Answers

You can use Rmagick's each_pixel method for this. each_pixel receives a block. For each pixel, the block is passed the pixel, the column number and the row number of the pixel. It iterates over the pixels from left-to-right and top-to-bottom.

So something like:

pixels = []

img.each_pixel do |pixel, c, r|
    pixels.push(pixel)
end
# pixels now contains each individual pixel of img
like image 68
Alex Avatar answered Sep 30 '22 22:09

Alex


I think Chunky PNG should do it for you. It's pure ruby, reasonably lightweight, memory efficient, and provides access to pixel data as well as image metadata.

like image 22
Phrogz Avatar answered Oct 01 '22 00:10

Phrogz