-
Notifications
You must be signed in to change notification settings - Fork 4
/
scan.go
65 lines (56 loc) · 1.53 KB
/
scan.go
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
package main
import (
"errors"
"github.com/kbinani/screenshot"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/oned"
"github.com/makiuchi-d/gozxing/qrcode"
)
// Scans the screen (all available) if it contains any supported barcode and tries to decode it.
// Returns a successfully decoded barcode value or an error.
func ScanScreenBarcode() (string, error) {
n := screenshot.NumActiveDisplays()
var lastErr error
for i := 0; i < n; i++ {
bounds := screenshot.GetDisplayBounds(i)
img, err := screenshot.CaptureRect(bounds)
if err != nil {
panic(err)
}
bmp, err := gozxing.NewBinaryBitmapFromImage(img)
if err != nil {
panic(err)
}
hints := map[gozxing.DecodeHintType]interface{}{gozxing.DecodeHintType_TRY_HARDER: true}
reader := oned.NewCodaBarReader()
result, err := reader.Decode(bmp, hints)
if err == nil {
return result.GetText(), nil
}
reader = oned.NewCode128Reader()
result, err = reader.Decode(bmp, hints)
if err == nil {
return result.GetText(), nil
}
reader = oned.NewCode39Reader()
result, err = reader.Decode(bmp, hints)
if err == nil {
return result.GetText(), nil
}
reader = oned.NewMultiFormatUPCEANReader(hints)
result, err = reader.Decode(bmp, hints)
if err == nil {
return result.GetText(), nil
}
reader = qrcode.NewQRCodeReader()
result, err = reader.Decode(bmp, hints)
if err == nil {
return result.GetText(), nil
}
lastErr = err
}
if lastErr != nil {
return "", lastErr
}
return "", errors.New("could not find a barcode")
}