Mercurial > lasercutter
view graster/graster/lib/graster/image.rb @ 11:f952052e37b7
trying a fix.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Tue, 24 Aug 2010 19:06:45 -0400 |
parents | |
children |
line wrap: on
line source
1 class Graster2 class Image3 PROPS = [:filename,:size,:pixels]5 def initialize(props)6 PROPS.each do |p|7 raise "required image property :#{p} missing" unless props[p]8 instance_variable_set "@#{p}", props[p]9 end10 end12 PROPS.each{|p| attr_reader p }14 def self.from_file pathname15 raise "file not found #{pathname}" unless File.exist? pathname16 img = Magick::Image.read(pathname)17 raise "bad image data in #{pathname}" unless img = img[0]18 new :filename => File.basename(pathname),19 :size => [img.columns,img.rows],20 :pixels => img.export_pixels(0,0,img.columns,img.rows,"I")21 end23 # get pixel(s) from x,y coords24 # 0,0 is bottom,left25 # image[x,y] => pixel at x,y26 # image[y] => row at y27 def [] y, x=nil28 if x29 @pixels[(@size[1]-y)*@size[0]+x]30 else31 @pixels[(@size[1]-y)*@size[0],@size[0]]32 end33 end35 def each_row &block36 @pixels.chars.each_slice(@size[0]).each_with_index &block37 end39 # "encode" a float 0..1 to a pixel40 def self.f_to_pix f41 (f*65535).round42 end44 # "decode" an encoded pixel to a float 0..145 def self.pix_to_f pix46 pix/65535.047 end50 # convert bitmap data to spans (or runs) of contiguous pixels51 # also invert the Y axis52 def build_spans on_range53 # TODO: rewrite in terms of each_row54 @spans = Array.new @size[1]56 @size[1].times do |y|57 spans = []58 left = (@size[1]-y-1)*@size[0]59 start = nil61 @size[0].times do |x|62 d = on_range.include?(@pixels[left+x])64 if !start && d65 start = x66 elsif start && !d67 spans << [start, x]68 start = nil69 end70 end72 spans << [start, @size[0]] if start73 @spans[y] = spans74 end75 end77 attr_reader :spans79 def hash80 [@pixels,@width,@height].hash81 end82 end83 end