github.com/mundipagg/boleto-api@v0.0.0-20230620145841-3f9ec742599f/boleto/img.go (about)

     1  package boleto
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/base64"
     6  	"image"
     7  	"image/draw"
     8  	"image/png"
     9  	
    10  	s "strings"
    11  	"github.com/golang/freetype"
    12  	"github.com/mundipagg/boleto-api/util"
    13  	"golang.org/x/image/font"
    14  )
    15  
    16  func textToImage(text string) string {
    17  	
    18  	if s.Contains(text,"  ") {		
    19  		text = s.Replace(text," ","",-1)
    20  		text = s.Replace(text,".","",-1)	
    21  		text = formatDigitableLine(text)
    22  	}
    23  	
    24  	size := float64(13)
    25  	dpi := float64(100)
    26  	rgba := image.NewNRGBA64(image.Rect(0, 0, 530, 20))
    27  	draw.Draw(rgba, rgba.Bounds(), image.Transparent, image.ZP, draw.Src)
    28  	c := freetype.NewContext()
    29  	c.SetDPI(dpi)
    30  	c.SetFont(util.GetFont().FtFont)
    31  	c.SetFontSize(size)
    32  	c.SetClip(rgba.Bounds())
    33  	c.SetDst(rgba)
    34  	c.SetSrc(image.Black)
    35  	c.SetHinting(font.HintingNone)
    36  
    37  	pt := freetype.Pt(10, 8+int(c.PointToFixed(size)>>7))
    38  	for _, s := range []string{text} {
    39  		c.DrawString(s, pt)
    40  		pt.Y += c.PointToFixed(size)
    41  	}
    42  
    43  	data := bytes.NewBuffer(nil)
    44  	png.Encode(data, rgba)
    45  	return base64.StdEncoding.EncodeToString(data.Bytes())
    46  }
    47  
    48  func formatDigitableLine(s string) string {
    49  	buf := bytes.Buffer{}
    50  	for idx, c := range s {
    51  		if idx == 5 || idx == 15 || idx == 26 {
    52  			buf.WriteString(".")
    53  		}
    54  		if idx == 10 || idx == 21 || idx == 32 || idx == 33 {
    55  			buf.WriteString(" ")
    56  		}
    57  		buf.WriteByte(byte(c))
    58  	}
    59  	return buf.String()
    60  }