Golang : Generate Datamatrix barcode

Datamatrix barcode is popular in the electronics, technology, arts and food industry as a way to mark small items. As it can encode up to 50 characters comparing to other barcode standards.

We will learn how to generate data matrix barcode in this tutorial. Code example adapted from previous barcode tutorials.

Here you go :

 package main

 import (

 func main() {

 code := "Datamatrix for Socketloop.com"

 fmt.Println("Generating Datamatrix barcode for : ", code)

 // see https://godoc.org/github.com/boombuler/barcode/datamatrix
 bcode, err := datamatrix.Encode(code)

 if err != nil {
 fmt.Printf("String %s cannot be encoded\n", code)

 // scale to 100x100
 bcode, err = barcode.Scale(bcode, 100, 100)

 if err != nil {
 fmt.Println("Datamatrix scaling error : ", err)

 // now we want to append the code at the bottom
 // of the Codabar

 // Create an new image with text data
 // From https://github.com/llgcode/draw2d.samples/tree/master/helloworld
 // Set the global folder for searching fonts

 // Initialize the graphic context on an RGBA image
 img := image.NewRGBA(image.Rect(0, 0, 250, 50))

 // set background to white
 white := color.RGBA{255, 255, 255, 255}
 draw.Draw(img, img.Bounds(), &image.Uniform{white}, image.ZP, draw.Src)

 gc := draw2d.NewGraphicContext(img)


 // Set the font Montereymbi.ttf
 gc.SetFontData(draw2d.FontData{"Monterey", draw2d.FontFamilyMono, draw2d.FontStyleBold | draw2d.FontStyleItalic})
 // Set the fill text color to black

 gc.FillStringAt(code, 50, 20)

 // create a new blank image with white background
 newImg := imaging.New(400, 200, color.NRGBA{255, 255, 255, 255})

 //paste the codabar to new blank image
 newImg = imaging.Paste(newImg, bcode, image.Pt(150, 30))

 //paste the text to the new blank image
 newImg = imaging.Paste(newImg, img, image.Pt(50, 150))

 err = draw2d.SaveToPngFile("./datamatrix.png", newImg)

 if err != nil {

 // everything ok
 fmt.Println("Datamatrix barcode generated and saved to datamatrix.png")


Sample output :

datamatrix golang

References :



  See also : Golang : How to generate Code 39 barcode?

By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.