2012-01-31 24 views
2

我需要操縱rmagick中的圖像的每個像素。我在IRB(交互式紅寶石)這樣做這是我有:Rmagick each_pixel,它是如何工作的?

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. 

我在做什麼錯?

回答

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 
+1

哈!忘了這一點,谷歌搜索同樣的問題,並發現這一點:)再次感謝布賴斯:) – Automatico 2014-04-06 11:26:19

相關問題