Class: ImageParser

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

Overview

Image Parser

Supports PPM and PTF file formats.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = nil) ⇒ ImageParser

Can be nil, but then it won’t create the file descriptor.



12
13
14
# File 'lib/imageparser.rb', line 12

def initialize(file=nil)
	@con = File.read(file, mode: 'rb') if file
end

Instance Attribute Details

#conObject

File descriptor reading accessor



6
7
8
# File 'lib/imageparser.rb', line 6

def con
  @con
end

Instance Method Details

#parse_ppm(info) ⇒ Object

Parse a PPM file.

Add parsed results into the hash ‘info`. These results are, the header, the width, the height, the RGB max value, the raster and the raster grid. Example: parse_ppm(hash)

> hash = “P6”, hash = 4, hash = 4, hash = 255,

> hash = [255, 42, 55, ..], hash = [[34, 43, 55], ..]



24
25
26
27
28
29
30
31
# File 'lib/imageparser.rb', line 24

def parse_ppm(info)
	info[:header] = @con.split(" ")[0] if @con.split(" ")[0] == "P6"
	info[:width] = @con.split(" ")[1].to_i if @con.split(" ")[1].to_i > 0 
	info[:height] = @con.split(" ")[2].to_i if @con.split(" ")[2].to_i > 0
	info[:rgb] = @con.split(" ")[3].to_i if @con.split(" ")[3].to_i > 0 && @con.split(" ")[3].to_i < 65536
	info[:raster] = @con.split(" ")[4..-1][0].unpack("C*") 
	info[:raster_grid] = info[:raster].each_slice(info[:width] * 3).to_a
end

#parse_ptf(info) ⇒ Object

Parse a PTF file.

Add parsed results into hash ‘info`. These results are, the header and the color information. Example: parse_ptf(hash) hash = “PTF1”, hash = [3, 2, 33, 3]



39
40
41
42
# File 'lib/imageparser.rb', line 39

def parse_ptf(info)
	info[:header] = @con.split(" ")[0] if @con.split(" ")[0] == "PTF1"
	info[:color_info] = @con.split(",")[1..-1].map {|s| s.delete ' '}
end