class Pnjson::Pnjson

Constants

HEADER_PNG

Attributes

chunks[RW]
header[RW]

Public Class Methods

new(filename) click to toggle source
# File lib/pnjson.rb, line 12
def initialize(filename)
  raw = File.open(filename).read
  hex_png = ascii_to_hex(raw)

  raw.close

  raise Error::InvalidPng unless valid_png?(hex_png)

  @header = hex_png.shift(8).join
  @chunks = chunkify(hex_png)
end

Public Instance Methods

chunkify(array) click to toggle source
# File lib/pnjson.rb, line 32
def chunkify(array)
  return [] if array.empty?
  length = convert_base(array.shift(4).join, 16, 10).to_i

  [Chunk.new({
    length: length,
    type: array.shift(4).join,
    data: array.shift(length).join,
    crc: array.shift(4).join
  }), chunkify(array)].flatten
end
to_json() click to toggle source
# File lib/pnjson.rb, line 24
def to_json
  { header: @header, chunks: @chunks.map { |c| c.to_hash }  }.to_json
end
valid_png?(hex_png) click to toggle source
# File lib/pnjson.rb, line 28
def valid_png?(hex_png)
  hex_png[0..7].join == HEADER_PNG
end

Private Instance Methods

ascii_to_hex(raw_str) click to toggle source
# File lib/pnjson.rb, line 46
def ascii_to_hex(raw_str)
  raw_str.each_byte.map do |byte|
    b = byte.to_s(16)
    b.length == 1 ? "0#{b}" : b
  end
end
convert_base(str, from, to) click to toggle source
# File lib/pnjson.rb, line 53
def convert_base(str, from, to)
  str.to_i(from).to_s(to)
end