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]) qr = RQRCode::QRCode.new(*(opts + [opthash]))
else
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
|