Class: Struggle::Code

Inherits:
Object
  • Object
show all
Defined in:
lib/struggle/code.rb

Class Method Summary collapse

Class Method Details

.getcode(w = 90, h = 40, fontsize = 24, wave = 5.5) ⇒ Object

controller def getcode

code = Code.getcode
session[:code]=code[:code]
send_data code[:img], content_type: 'image/jpeg', disposition: 'inline'

end view <img src=“/getcode”> Code.getcode(90,40,24) w宽,h高,fontsize字体大小 返回json类型



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/struggle/code.rb', line 15

def self.getcode(w=90, h=40, fontsize=24, wave=5.5)
  #创建画布
  img = Magick::Image.new(w, h) {
    self.background_color = 'white'
    self.format="JPG"
  }
  text= Magick::Draw.new
  text.pointsize = fontsize
  text.kerning = -1
  filePath = File.expand_path(File.dirname(File.dirname(__FILE__)))
  fontPath = File.expand_path("struggle/font/ARIALNBI.TTF", filePath)
  text.font(fontPath)
  text.font_weight(200)
  text.fill('blue')
  # 随机文字
  code=""
  4.times { code << (97 + rand(26)).chr }
  # 设置文字
  text.text(rand(w/2-5), h/2 + rand(-2..2), code)
  # 随机直线
  for i in 1..rand(5)
    text.line(rand(w), rand(h), rand(w), rand(h)) #直线
  end
  text.fill('blue')
  # 燥点
  for i in 1..20
    text.point(rand(w), rand(h))
  end
  text.draw(img)
  #模糊
  # img = img.sketch(0, 10, 50)
  #扭曲
  img = img.wave(wave, 70)
  #返回图片数据流
  {img: img.to_blob, code: code}
end