forked from JackDanger/barcodeservice
/
barcode_service.rb
107 lines (88 loc) · 2.39 KB
/
barcode_service.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
## Resources
require 'rubygems'
gem 'sinatra' #, '~> 1.0.0'
require 'sinatra'
gem 'gbarcode'
require 'gbarcode'
## Application
get '/:code.:extension' do
begin
options = request.env['rack.request.query_hash']
options = default_options.merge(options)
content_type "image/#{params[:extension]}"
headers['Cache-Control'] = "public, max-age=#{3600*24*365}"
Converter.encode params[:code], params[:extension], options
rescue => error
puts error.inspect
status 400
end
end
get '/' do
%Q{
<body style='line-height: 1.8em; font-family: Archer, Museo, Helvetica, Georgia; font-size 25px; text-align: center; padding-top: 20%;'>
Get a barcode image by crafting a url at this domain.
<pre style='font-family: Iconsolata, monospace;background-color:#EEE'><img src="http://#{request.host}/12345632323.png" /></pre>
<br />
<img src="/12345632323.png" />
</body
}
end
## HELPERS
def default_options
{
'type' => 'any',
'output' => 'png',
'width' => 100,
'height' => 50,
'x' => 0,
'y' => 0,
'margin' => 0,
'scale' => 0
}
end
TYPES = {
'any' => 'BARCODE_ANY',
'ean' => 'BARCODE_EAN',
'upc' => 'BARCODE_UPC',
'isbn' => 'BARCODE_ISBN',
'128b' => 'BARCODE_128B',
'128C' => 'BARCODE_128C',
'128' => 'BARCODE_128',
'128raw' => 'BARCODE_128RAW',
'39' => 'BARCODE_39',
'I25' => 'BARCODE_I25',
'cbr' => 'BARCODE_CBR',
'msi' => 'BARCODE_MSI',
'pls' => 'BARCODE_PLS',
'93' => 'BARCODE_93'
}
module Converter
include Gbarcode
extend Gbarcode
def self.encode(code, format, options)
require 'stringio'
barcode = barcode_create(code)
barcode.width = options['width'].to_i
barcode.height = options['height'].to_i
barcode.xoff = options['x'].to_i
barcode.yoff = options['y'].to_i
barcode.scalef = options['scale'].to_i
barcode_encode barcode, BARCODE_NO_CHECKSUM | const_get(TYPES[options['type']])
file = Tempfile.new('barcode')
File.open(file.path, 'w') do |f|
barcode_print(barcode, f, BARCODE_OUT_EPS)
end
output = case format
when 'eps'
file.read
when "png"
%x{convert eps:#{file.path} png:-}
when "jpg", "jpeg"
%x{convert eps:#{file.path} jpg:-}
when "gif"
%x{convert eps:#{file.path} gif:-}
end
file.unlink
output
end
end