我需要在rmagick中操纵图像的每个像素。我在IRB(互动红宝石)中这样做这就是我所拥有的:
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.
我做错了什么?
答案 0 :(得分:7)
问题是,您从each_pixel返回的数组是一个新数据集。需要将数据存储回图像。
改为使用get_pixels和store_pixels:
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