映像の仕事で特定の画像パターンを簡単に生成するために作ったツールです。
上から2/3くらい下にある、##### start というコメントの下にコマンドを書いて実行すると、PPMファイルが生成できます。
生成されたPPMファイルを、ほかの画像アプリでBMPなどに変換して使うことを想定しています。
#!/usr/bin/ruby -w
class Canvas
def initialize(w,h,color)
@w = w
@h = h
@canvas = Array.new(w){ Array.new(h,color) }
end
def checkArea(ptr)
if(ptr.i_x >= 0 && ptr.i_x <= (@w-1) &&
ptr.i_y >= 0 && ptr.i_y <= (@h-1))then
return true
else
return false
end
end
def putDot(ptr,color)
if(checkArea(ptr))then
@canvas[ptr.i_x][ptr.i_y] = color
end
end
def drawLine(ptr0,ptr1,color)
if(ptr0.f_x < ptr1.f_x)then
x0 = ptr0.f_x
x1 = ptr1.f_x
y0 = ptr0.f_y
y1 = ptr1.f_y
else
x0 = ptr1.f_x
x1 = ptr0.f_x
y0 = ptr1.f_y
y1 = ptr0.f_y
end
f_len = Math.sqrt((x1-x0)**2 + (y1-y0)**2)
i_len = f_len.to_i
#puts "len=#{i_len}"
divx = (x1-x0)/f_len
divy = (y1-y0)/f_len
i_len.times do |num|
x = x0 + divx*(num.to_f + 1.0)
y = y0 + divy*(num.to_f + 1.0)
#puts "(x,y) = (#{x.to_i},#{y.to_i})"
putDot(Pointer.new(x,y),color)
end
end
def printOut(filename=nil)
if(filename==nil)then
$stdout = STDOUT
else
$stdout = File.open(filename, "w")
puts "P3"
puts "# create by tomosuke"
puts "#{@w} #{@h}"
puts "255" #brightness
@h.times do |y|
@w.times do |x|
r = @canvas[x][y].i_r
g = @canvas[x][y].i_g
b = @canvas[x][y].i_b
printf("%d %d %d ", r,g,b)
end
end
$stdout = STDOUT
end
end
end
class Color
def initialize(r,g,b)
@f_r = clip(r.to_f,255.0,0.0)
@f_g = clip(g.to_f,255.0,0.0)
@f_b = clip(b.to_f,255.0,0.0)
@i_r = clip(r.to_i,255,0)
@i_g = clip(g.to_i,255,0)
@i_b = clip(b.to_i,255,0)
end
def clip(var,max,min)
if(var > max)then
return max
elsif(var < min)then
return min
else
return var
end
end
attr_accessor :i_r,:i_g,:i_b
end
class Pointer
def initialize(x,y)
@i_x = x.to_i
@i_y = y.to_i
@f_x = x.to_f
@f_y = y.to_f
end
attr_accessor :i_x, :i_y, :f_x, :f_y
end
##### start
color = Color.new(255,255,255)
canvas = Canvas.new(256,256,color)
color = Color.new(0,0,255)
#for i in 10..20 do
# ptr = Pointer.new(10+i,10+i)
# canvas.putDot(ptr,color)
#end
offset = -20
step = 5
for i in 0..99 do
ptr0 = Pointer.new(offset + i*step, 0)
ptr1 = Pointer.new(offset + 20 + i*step, 200)
canvas.drawLine(ptr0,ptr1,color)
end
canvas.printOut("hoge.ppm")
##### end