```go
package main
import (
"image/png"
"os"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/oned"
"fmt"
)
func encode(content, savePath string, width, height int) error {
enc := oned.NewCode128Writer()
img, err := enc.Encode(content, gozxing.BarcodeFormat_CODE_128, width, height, nil)
if err != nil {
return err
}
file, err := os.Create(savePath)
if err != nil {
return err
}
defer file.Close()
return png.Encode(file, img)
}
func decode(file string) (content string, err error) {
f, err := os.Open(file)
if err != nil {
return content, err
}
img, err := png.Decode(f)
if err != nil {
return content, err
}
dec := oned.NewCode128Reader()
i, err := gozxing.NewBinaryBitmapFromImage(img)
if err != nil {
return content, err
}
r, err := dec.DecodeWithoutHints(i)
if err != nil {
return content, err
}
return r.String(), err
}
func main() {
file := "barcode.png"
if err := encode("barcode", file, 120, 60); err != nil {
fmt.Println("encode error:", err)
return
}
fmt.Println("encode success!")
content, err := decode(file)
if err != nil {
fmt.Println("decode error:", err)
return
}
fmt.Println(content)
}
```
有疑问加站长微信联系(非本文作者))