8

Go语言读写条形码 - Go语言中文网 - Golang中文社区

 1 year ago
source link: https://studygolang.com/articles/35663
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Go语言读写条形码

574499439 · 大约5小时之前 · 131 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

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)
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK