gem install rqrcode
or
gem 'rqrcode', '~> 0.7.0'
废话不多说,直接上代码
class Tool < ActiveRecord::Base
def self.generate_rqrcode(url, options={})
options = {size: 150 ,size_start: 3, size_end: 3,set_start: 1, set_end: 40}.merge(options)
# Rails.logger.info "==生成二维码=="
qrcode = RQRCode::QRCode.new(url)
png = qrcode.as_png(
resize_gte_to: false,
resize_exactly_to: false,
fill: 'white',
color: 'black',
border_modules: 2,
size: options[:size],
setQrcodeVersion: options[:set_start] - options[:set_end],
box_size: options[:size_start] * options[:size_end],
module_px_size: 8,
file: nil
)
new_file_name = Time.now.to_i.to_s + rand(10000000).to_s + '.png'
# 生成好的二维码会放在public/uploads/rqrcode/这个目录下。
path = "#{Rails.root}/public/uploads/rqrcode/#{new_file_name}"
png.save(path)
binary_string = png.to_blob
# Rails.logger.info "== binary_string == #{binary_string.inspect}"
# Rails.logger.info "==生成二维码成功=url=#{url}"
return url
end
#把这个方法写在controller(根据需要重写这个方法)
#def share_with_rqrcode
# rqrcode_url = Tool.generate_rqrcode 'www.baidu.com'
# render json: {
# rqrcode_url: rqrcode_url
# }
#end
end