f8g

IronRubyを使ってみた

簡単な画像処理を。
http://www.microsoft.com/japan/msdn/academic/Articles/Algorithm/03/ の3.2.2。

require 'mscorlib'
require 'System.Drawing'
require 'System.Windows.Forms'

img_file = "img.bmp"

form = System::Windows::Forms::Form.new()
form.width  = 300
form.height = 150

pictures = [
	System::Windows::Forms::PictureBox.new(),
	System::Windows::Forms::PictureBox.new()
]

pictures.each {|picture|
	picture.width  = 120
	picture.height = 120
	form.controls.add(picture)
}

pictures[1].left  = 150
pictures[0].image = System::Drawing::Image::FromFile(img_file)
pictures[1].image = System::Drawing::Bitmap.new(pictures[0].width, pictures[1].height)

pictures[0].image.width.times {|x|
	pictures[0].image.height.times {|y|
		pixel = pictures[0].image.getPixel(x, y)
		( (0 + pixel.R + pixel.G + pixel.B) / 3 > 128 )?
			pictures[1].image.setPixel(x, y, System::Drawing::Color.white):
			pictures[1].image.setPixel(x, y, System::Drawing::Color.Black)
	}
}
puts "load"
form.showDialog()

あんまりRubyっぽく書けてないかも。Color#Rなんかが.NETのByteオブジェクトで、0+を付けてやらないと和が計算できなかった気がした。あと、何か横長くなるな。