How to Draw Chinese on QR Code with Ruby

Roger Wang
2 min readNov 29, 2017

--

Prepare

Tools

Here’s a to-install list, add in your Gemfile:

  1. rQRCode + rqrcode_png— generate QR code
gem 'rqrcode_png'

2. RMagick — Draw text on image

gem 'rmagick'

3. ImageMagick — Core engine of RMagick

4. And You need a Font type to draw Chinese. I prefer LiHei Pro

P.S. Why you need a Font type to implement Chinese drawing?

At my first try, every Chinese change to ?. You think it’s a encoding issue? Nope, It’s about Drawing issue. The default font type can’t draw UTF-8 into Chinese. So we need a new Font Type.
You can know about how to add a Font Type in Ubuntu here.

Steps

  1. Generate QR code from url
qr_code_img = RQRCode::QRCode.new("https://www.google.com").as_png(
resize_gte_to: false,
resize_exactly_to: false,
fill: 'white',
color: 'black',
size: 480,
border_modules: 4,
module_px_size: 6,
file: "google_qrcode.png" # path to write
)

You can also save image as SVG, HTML or ANSI string by simply call method.

require 'rqrcode'

qrcode = RQRCode::QRCode.new("http://github.com/")
image = qrcode.as_png
svg = qrcode.as_svg
html = qrcode.as_html
string = qrcode.as_ansi
string = qrcode.to_s

Then we have the QR code

2. Draw down your text

img = ImageList.new("google_qrcode.png")
txt = Draw.new
txt.font = '/usr/share/fonts/truetype/lihei-pro.ttf'

img.annotate(txt, 0,0,0,10, c.name.force_encoding("UTF-8")){
txt.gravity = Magick::SouthGravity
txt.pointsize = 25
txt.fill = '#000000'
}
file = File.new("google_final.png", File::CREAT|File::TRUNC|File::RDWR, 0644)img.write(file)

Parameters of .annotate is ( Draw draw, width, height, x, y, “text to add”)

And you can change the gravity on image and the Font style.

In my case, the output image:

Special Issues

Cool, and I just found a little problem.

Because I use rails c to run these method. And my image crash until I exit consle. I don’t know why, really have no idea.

But, Okay. It still good stuff that help me so much.

Thanks for finished my article. If you like it, please give me some claps and follow my channel. See you next time~

--

--

No responses yet