Generate QR code images in Ruby on Rails app

Create a QR code image along with some content written below it.

Sample Image

Assuming a Rails app is set-up along with ImageMagick. Storing the generated image on S3.

  1. Add rqrcode gem in your gemfile
    gem 'rqrcode'
  2. If you just want an image with QR code, the code below will create an image of size 500 for you. Where qr_code is an object with code method returning the content to be embedded into it.
    file = Tempfile.new(["qr", '.png'])
    File.open(file, 'wb') do |f|
      f.write(RQRCode::QRCode.new(qr_code.code).as_png(size: 500).to_s)
    end
  3. To add content below the QR code as shown in sample image. Follow on.
    Take an empty image of required resolution for the content below the QR code and add it in your Rails directory. I have created doc/qr/ for this.
  4. Once the image is added into the directory we will use ImageMagick to add content on it and merge with QR code image. I am using rmagick gem, minimagick should also work just fine.
  5. The following code adds the required content on the sample image and stores inside the tmp directory.
    content_image = Magick::Image.read("#{Rails.root.to_s}/doc/qr/content_base.jpg").first 
    
    draw_content = Magick::Draw.new 
    draw_content.pointsize(100) 
    draw_content.text_align(Magick::CenterAlign) 
    draw_content.font_weight(Magick::BoldWeight) 
    draw_content.fill('#000000') 
    draw_content.text(250, 80, qr_code.content) 
    draw_content.draw(content_image) 
    
    content_image.write("#{Rails.root.to_s}/tmp/number-#{qr_code.code}.jpg")Now merge those two generated images
  6. qr_image = Magick::Image.read(file.path).first 
    
    imagelist = Magick::ImageList.new 
    
    imagelist.push(qr_image) 
    imagelist.push(content_image) 
    
    imagelist.append(true).write("#{Rails.root}/tmp/qr-code-#{qr_code.code}.jpg"
    
  7. Upload to S3
    s3 = Aws::S3::Resource.new(region: ENV['AWS_REGION']) 
    obj = s3.bucket(ENV['S3_BUCKET']).object(qr_code.upload_path) 
    obj.upload_file("#{Rails.root}/tmp/qr-code-#{qr_code.code}.jpg", acl: 'public-read')
  8. That’s all folks

    Leave a comment if you have any doubts.

Leave a comment

Your email address will not be published. Required fields are marked *