Create QR code and render it as PNG image in Rails
A tutorial to create QR code in your Rails application.
What is QR code for website?
QR (Quick Response) codes are a great tool to drive traffic. When someone uses a smartphone to scan your QR code, they are brought directly to any webpage you specify.
For QR code creation and rendering need to follow two simple steps:-
Step 1. Create QR code
Add this line to your application’s Gemfile
gem "rqrcode"
then run bundle install
Run below command to generate QR code
qr_code = RQRCode::QRCode.new(“http://github.com/")
qr_as_svg = qr_code.as_svg( color: “000”, shape_rendering: “crispEdges”, module_size:11,
standalone: true,
use_path: true
)
Now you get the QR code in svg format.
You can display it using below code
<%= raw qr_as_svg.html_safe %>
Step 2. Convert QR code SVG to PNG image
For converting SVG to PNG, we need to add mini_magick gem in gemfile
gem ‘mini_magick’
now use this below code snippet
qr_code_image = MiniMagick::Image.read(your_svg_object) { |i| i.format “svg” }
qr_code_image.format “png”
This is how you will get the QR code in PNG format.
If you liked this post, please click on ✋ to spread the word.