Search code examples
rubypixelrmagick

Rmagick each_pixel, how does it work?


I need to manipulate each pixel of an image in rmagick. I am doing this in IRB(interactive ruby) This is what I have:

require 'Rmagick'
include Magick
f = Image.new(100,100)
f.display #so far so good. A 100x100 white image is displayed

f.each_pixel {|pixel, c, r| pixel.red = 0}
f.display #the image is still white. It should really be a shade of blue.

What am I doing wrong?


Solution

  • The thing is, the array you get back from each_pixel is a new dataset. The data needs to be stored back to the image.

    Use get_pixels and store_pixels instead:

    img = Magick::ImageList.new('img.jpg').first
    pixels = img.get_pixels(0,0,img.columns,img.rows)
    
    for pixel in pixels
        avg = (pixel.red + pixel.green + pixel.blue) / 3
        pixel.red = avg
        pixel.blue = avg
        pixel.green = avg
    end
    
    img.store_pixels(0,0, img.columns, img.rows, pixels)
    img.display