#!/usr/local/bin/ruby
# QRcode image library 0.50beta6  (c)2002-2004 Y.Swetake
# modified by Kouichirou Eto

class QRCodeImage
  def initialize(path)
    @qrcode = QRCode.new(path)
  end

  def generate(d)
    generate_png_from_data(@qrcode.make_qrcode(d))
  end

  def generate_png_from_data(data)
    mkimage(data).pngStr
  end

  def mkimage(data, m=2, q=4)
    begin
      require "GD"
    rescue LoadError, Exception => err
      return nil
    end

    raise unless 0 < m && m < 9
    raise unless 0 < q && q < 9

    module_size = m
    quiet_zone  = q

    data_array = data.split("\n")
    image_size = data_array.size

    output_size = (image_size + quiet_zone * 2) * module_size

    img = GD::Image.new(image_size, image_size) # original image

    white = img.colorAllocate(255, 255, 255)
    black = img.colorAllocate(0, 0, 0)

    im = GD::Image.new(output_size, output_size) # canvas with quiet zone

    white2 = im.colorAllocate(255, 255, 255)
    im.fill(0, 0, white2)

    data_array.each_with_index {|row, y|
      (0..image_size).each {|x|
	if (row[x,1] == "1")
	  img.setPixel(x, y, black)
	end
      }
    }

    quiet_zone_offset = quiet_zone * module_size
    image_width = image_size * module_size
    img.copyResized(im, quiet_zone_offset, quiet_zone_offset, 0, 0,
		    image_width, image_width, image_size, image_size)
    im
  end
end
