Generating QR code images with rqrcode
10th Aug 2011I was playing with the rqrcod gem to generate QR codes when I realized it wasn't prepared to output an image. This library provides an easy way to iterate over the generated matrix and detect the black modules, so it should be a straightforward task:
require "rqrcode" require "chunky_png" module RQRCode class QRCode # to_image # # the size parameter indicates the width and height in pixels for each module def to_image(size) image = ChunkyPNG::Image.new(size * @modules.size, size * @modules.size, ChunkyPNG::Color::WHITE) @modules.each_index do |x| @modules.each_index do |y| if (self.dark?(x,y)) image.rect(x * size, y * size, (x * size) + size, (y * size) + size, ChunkyPNG::Color::BLACK, ChunkyPNG::Color::BLACK) end end end image end end end
Then we could write a simple qr-code generator with a rack middleware:
class RackQR def call(env) text = Rack::Request.new(env).GET["text"] qr = RQRCode::QRCode.new(text) image = qr.to_image(5) [200, {"Content-type" => "image/png"}, [image.to_blob]] end end

????? Tai Kung Machine Factory
2 months ago