Class: Graster::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/graster/image.rb

Constant Summary collapse

PROPS =
[:filename,:size,:pixels]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(props) ⇒ Image

Returns a new instance of Image.



5
6
7
8
9
10
# File 'lib/graster/image.rb', line 5

def initialize(props)
  PROPS.each do |p|
    raise "required image property :#{p} missing" unless props[p]
    instance_variable_set "@#{p}", props[p]
  end
end

Instance Attribute Details

#spansObject (readonly)

Returns the value of attribute spans.



77
78
79
# File 'lib/graster/image.rb', line 77

def spans
  @spans
end

Class Method Details

.f_to_pix(f) ⇒ Object

“encode” a float 0..1 to a pixel



40
41
42
# File 'lib/graster/image.rb', line 40

def self.f_to_pix f
  (f*65535).round
end

.from_file(pathname) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/graster/image.rb', line 14

def self.from_file pathname
  raise "file not found #{pathname}" unless File.exist? pathname
  img = Magick::Image.read(pathname)
  raise "bad image data in #{pathname}" unless img = img[0]
  new :filename => File.basename(pathname),
      :size => [img.columns,img.rows],
      :pixels => img.export_pixels(0,0,img.columns,img.rows,"I")
end

.pix_to_f(pix) ⇒ Object

“decode” an encoded pixel to a float 0..1



45
46
47
# File 'lib/graster/image.rb', line 45

def self.pix_to_f pix
  pix/65535.0
end

Instance Method Details

#[](y, x = nil) ⇒ Object

get pixel(s) from x,y coords 0,0 is bottom,left image => pixel at x,y image => row at y



27
28
29
30
31
32
33
# File 'lib/graster/image.rb', line 27

def [] y, x=nil
  if x
    @pixels[(@size[1]-y)*@size[0]+x]
  else
    @pixels[(@size[1]-y)*@size[0],@size[0]]
  end
end

#build_spans(on_range) ⇒ Object

convert bitmap data to spans (or runs) of contiguous pixels also invert the Y axis



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/graster/image.rb', line 52

def build_spans on_range
  # TODO: rewrite in terms of each_row
  @spans = Array.new @size[1]

  @size[1].times do |y|
    spans = []
    left = (@size[1]-y-1)*@size[0]
    start = nil

    @size[0].times do |x|
      d = on_range.include?(@pixels[left+x])

      if !start && d
        start = x
      elsif start && !d
        spans << [start, x]
        start = nil
      end
    end

    spans << [start, @size[0]] if start
    @spans[y] = spans
  end
end

#each_row(&block) ⇒ Object



35
36
37
# File 'lib/graster/image.rb', line 35

def each_row &block
  @pixels.chars.each_slice(@size[0]).each_with_index &block
end

#hashObject



79
80
81
# File 'lib/graster/image.rb', line 79

def hash
  [@pixels,@width,@height].hash
end