Class: Pngqr

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

Class Method Summary collapse

Class Method Details

.encode(*opts) ⇒ Object



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
43
44
45
46
47
48
49
50
51
52
# File 'lib/pngqr.rb', line 8

def encode(*opts)
  opthash = {}
  if Hash===opts.last
    opthash = opts.pop
    @filename = opthash.delete(:file) 
    @scale = opthash.delete(:scale)
    @border = opthash.delete(:border)
  end
  @scale ||= 1
  @border ||= 0

  qr = nil
  if(opthash[:size]) # user supplied size
    qr = RQRCode::QRCode.new(*(opts + [opthash]))
  else
    # autosize algorithm: start at size=1 and increment until it worked
    opthash[:size] = 1
    while qr.nil?
      qr = begin
        RQRCode::QRCode.new(*(opts + [opthash]))
      rescue RQRCode::QRCodeRunTimeError => e
        opthash[:size] += 1
        raise unless e.to_s =~ /overflow/ && opthash[:size] <= 40
      end
    end
  end
  len = qr.module_count
  png = ChunkyPNG::Image.new(len*@scale + 2*@border, len*@scale + 2*@border, ChunkyPNG::Color::WHITE)
  
  for_each_pixel(len) do |x,y|
    if qr.modules[y][x]
      for_each_scale(x, y, @scale) do |scaled_x, scaled_y|
        png[scaled_x + @border, scaled_y + @border] = ChunkyPNG::Color::BLACK
      end
    end
  end
  
  blob = png.to_blob(:fast_rgb)
  blob = blob.force_encoding('ASCII-8BIT') if blob.respond_to?(:force_encoding)
  if @filename
    File.open(@filename, 'wb') {|io| io << blob }
  else
    blob
  end
end