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 =["qr", '.png']), 'wb') do |f|
      f.write( 500).to_s)
  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 ="#{Rails.root.to_s}/doc/qr/content_base.jpg").first 
    draw_content = 
    draw_content.text(250, 80, qr_code.content) 
    content_image.write("#{Rails.root.to_s}/tmp/number-#{qr_code.code}.jpg")Now merge those two generated images
  6. qr_image = 
    imagelist = 
  7. Upload to S3
    s3 = 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 *