Class: Compass::PNG

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

Overview

A simple class to represent and create a PNG-File No drawing features given Just subclass and write [R,G,B]-Byte-Values into the @data matrix Build for compactness, so not much error checking!

Code based on seattlerb's png, see seattlerb.rubyforge.org/png/

Direct Known Subclasses

GridBuilder

Constant Summary

CRC_TABLE =
(0..255).map do |n|
  (0...8).inject(n){|x,i| x = ((x & 1) == 1) ? 0xedb88320 ^ (x >> 1) : x >> 1}
end
BITS =
8
RGB =
2
NONE =

Color Types ( RGBA = 6) Filter

0

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (PNG) initialize(width, height, background = [255,255,255])

Initiates a new PNG-Object

  • width: Width of the image in pixels

  • height: Height of the image in pixels

  • background: Background-color represented as [R,G,B]-Byte-Array



30
31
32
33
34
# File 'lib/compass/grid_builder.rb', line 30

def initialize(width, height, background = [255,255,255])
  @height = height
  @width = width
  @data = Array.new(@height) { |x| Array.new(@width, background) }
end

Class Method Details

+ (Object) chunk(type, data = "")



21
22
23
# File 'lib/compass/grid_builder.rb', line 21

def chunk(type, data="")
  [data.size, type, data, crc(type + data)].pack("Na*a*N")
end

+ (Object) crc(chunkdata = '')



17
18
19
# File 'lib/compass/grid_builder.rb', line 17

def crc(chunkdata='')
  chunkdata.unpack('C*').inject(0xffffffff){|crc, byte| CRC_TABLE[(crc ^ byte)  & 0xff] ^ (crc >> 8) } ^  0xffffffff
end

Instance Method Details

- (Object) png_join



50
51
52
# File 'lib/compass/grid_builder.rb', line 50

def png_join
  @data.map { |row| "\0" + row.map { |p| "%c%c%c" % p}.join }.join
end

- (Object) to_blob

binary representation of the PNG, write to file with binary mode



41
42
43
44
45
46
47
48
# File 'lib/compass/grid_builder.rb', line 41

def to_blob
  blob = []
  blob <<  [137, 80, 78, 71, 13, 10, 26, 10].pack("C*")
  blob << PNG.chunk('IHDR', [@width, @height, BITS, RGB, NONE, NONE, NONE].pack("N2C5"))
  blob << PNG.chunk('IDAT', Zlib::Deflate.deflate(self.png_join))
  blob << PNG.chunk('IEND', '')
  blob.join
end