golang中条码的生成
golang里条码生成可以调用
"github.com/boombuler/barcode/code128"实现,实例代码如下:
比如在gin方法中实现如下
{
code, err := code128.Encode("123abc") //根据字符串123abc生成条码
if err != nil {
ginplus.ResponseError(c, err)
return
}
codeScale, err := barcode.Scale(code, 350, 70) //生成一个宽为350,高为70的条码
img := subtitleBarcode(codeScale) //这个函数的作用是生成条码下面的数字
c.Header("Content-Type", "image/png")
png.Encode(c.Writer, img)
}
func subtitleBarcode(bc barcode.Barcode) image.Image {
fontFace := basicfont.Face7x13
fontColor := color.RGBA{0, 0, 0, 255}
margin := 5 // Space between barcode and text
// Get the bounds of the string
bounds, _ := font.BoundString(fontFace, bc.Content())
widthTxt := int((bounds.Max.X - bounds.Min.X) / 64)
heightTxt := int((bounds.Max.Y - bounds.Min.Y) / 64)
// calc width and height
width := widthTxt
if bc.Bounds().Dx() > width {
width = bc.Bounds().Dx()
}
height := heightTxt + bc.Bounds().Dy() + margin
// create result img
img := image.NewRGBA(image.Rect(0, 0, width, height))
// draw the barcode
draw.Draw(img, image.Rect(0, 0, bc.Bounds().Dx(), bc.Bounds().Dy()), bc, bc.Bounds().Min, draw.Over)
// TextPt
offsetY := bc.Bounds().Dy() + margin - int(bounds.Min.Y/64)
offsetX := (width - widthTxt) / 2
point := fixed.Point26_6{
X: fixed.Int26_6(offsetX * 64),
Y: fixed.Int26_6(offsetY * 64),
}
d := &font.Drawer{
Dst: img,
Src: image.NewUniform(fontColor),
Face: fontFace,
Dot: point,
}
d.DrawString(bc.Content())
return img
}
前端调用后效果如下:
大功告成@@@