Class: PNG

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

Overview

A pure Ruby Portable Network Graphics (PNG) writer.

www.libpng.org/pub/png/spec/1.2/

PNG supports: + 8 bit truecolor PNGs

PNG does not support: + any other color depth + extra data chunks + filters

Example

require 'png'

canvas = PNG::Canvas.new 200, 200
canvas[100, 100] = PNG::Color::Black
canvas.line 50, 50, 100, 50, PNG::Color::Blue
png = PNG.new canvas
png.save 'blah.png'

Defined Under Namespace

Classes: Canvas, Color

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(canvas) ⇒ PNG

Creates a new PNG object using canvas



67
68
69
70
71
72
# File 'lib/PatchedPNG.rb', line 67

def initialize(canvas)
  @height = canvas.height
  @width = canvas.width
  @bits = 8
  @data = canvas.data
end

Class Method Details

.chunk(type, data = "") ⇒ Object

Creates a PNG chunk of type type that contains data.



60
61
62
# File 'lib/PatchedPNG.rb', line 60

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

Instance Method Details

#raw_bytesObject



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/PatchedPNG.rb', line 89

def raw_bytes
	bytes=""
	bytes<< [137, 80, 78, 71, 13, 10, 26, 10].pack("C*") # PNG signature
	bytes<< PNG.chunk('IHDR',
		[ @height, @width, @bits, 6, 0, 0, 0 ].pack("N2C5"))
	# 0 == filter type code "none"
	data = @data.map { |row| [0] + row.map { |p| p.values } }.flatten
	bytes<< PNG.chunk('IDAT', Zlib::Deflate.deflate(data.pack("C*"), 9))
	bytes<< PNG.chunk('IEND', '')
	bytes
end

#save(path) ⇒ Object

Writes the PNG to path.



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/PatchedPNG.rb', line 77

def save(path)
  File.open(path, "w") do |f|
    f.write [137, 80, 78, 71, 13, 10, 26, 10].pack("C*") # PNG signature
    f.write PNG.chunk('IHDR',
                      [ @height, @width, @bits, 6, 0, 0, 0 ].pack("N2C5"))
    # 0 == filter type code "none"
    data = @data.map { |row| [0] + row.map { |p| p.values } }.flatten
    f.write PNG.chunk('IDAT', Zlib::Deflate.deflate(data.pack("C*"), 9))
    f.write PNG.chunk('IEND', '')
  end
end