介绍
随着智能手机的普及,越来越多Web应用都会将链接生成一个二维码,亦或者是如微信的二维码支付。
生成二维码并且使用有两种方式:第一种是固定重复的链接,这将会是被多次使用,那可以将这二维码图片保存到某个地方; 第二种是一次性使用(二维码支付),在需要的时候再去生成对应的二维码图片就可以。
以下代码均用Ruby来实现,使用 rqrcode_png Gem
一次性使用二维码图片
在 Rails Controller 中
qr = RQRCode::QRCode.new('http://mouseshi.com', size: 4, level: :h )
qrcode_str = Base64.encode64(qr.to_img.resize(300, 300).to_s)
在 Rails View 中
image_tag("data:image/png;base64,#{@qrcode_str}")
重复性使用二维码图片
require 'rqrcode_png'
qr = RQRCode::QRCode.new('http://mouseshi.com', size: 4, level: :h )
png = qr.to_img
png.resize(240, 240).save("mouseshi_website.png") # 保存到目录
上面代码可以做部分更改,使用 Ruby Tempfile Class 来实现保存图片
require 'rqrcode_png'
begin
qrcode_img = Tempfile.new('qrcode')
qr = RQRCode::QRCode.new('http://mouseshi.com', size: 4, level: :h )
png = qr.to_img
qrcode_img.write(png)
# 在这里可以实现保存你要的图片,对象 qrcode_img
ensure
qrcode_img.close!
end