Class: Pruim::PPM

Inherits:
Object
  • Object
show all
Includes:
Codec
Defined in:
lib/pruim/ppm.rb

Instance Method Summary collapse

Methods included from Codec

for_filename, for_filename_name, for_name, new_for_filename, new_for_filename_name, new_for_name, register, #text

Instance Method Details

#can_decode?(stream) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
65
66
# File 'lib/pruim/ppm.rb', line 62

def can_decode?(stream)
  header = stream.gets
  stream.rewind
  return header == "P3\n"
end

#can_encode?(image) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/pruim/ppm.rb', line 68

def can_encode?(image)
  return true
end

#decode(stream) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pruim/ppm.rb', line 6

def decode(stream)
  header = stream.gets
  lines  = []
  until stream.eof?
    lines << stream.gets
  end
  image   = nil
  page    = nil
  w, h, d = nil, nil
  y       = 0
  comment = ''
  lines.each do |line| 
    if line[0] == '#'
      comment << line.chomp.sub(/\A#/, '') 
      next
    end
    if !image
      w , h = line.chomp.split(' ').map { |v| v.to_i }
      image = Image.new(w, h)
      page  = image.new_page(w, h)
      next
    end
    if !d
      d = line.chomp.to_i
      next
    end
    triplets = line.chomp.split(' ').map { |v| v.to_i }
    for x in (0...page.w) do
      r, g, b = triplets.shift(3)
      color   = Color.rgb(r, g, b)
      page.putpixel(x, y, color)
    end
    y += 1 
  end
  image.comment = comment
  return image
end

#encode(image, stream) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/pruim/ppm.rb', line 45

def encode(image, stream)
  stream.puts("P3")
  stream.puts("##{image.comment}") if image.comment
  stream.puts("#{image.w} #{image.h}")
  stream.puts("255")
  page = image.pages.first
  for y in (0...page.h) do
    for x in (0...page.w) do
      color = page.getpixel!(x, y)
      r, g, b = Color.to_rgb(color)
      stream.write(" ") if x > 0
      stream.write("#{r} #{g} #{b}")
    end
    stream.write("\n")
  end
end

#encode_will_degrade?(image) ⇒ Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/pruim/ppm.rb', line 72

def encode_will_degrade?(image)
  return (image.pages.size > 1)
end