feat(barcode): Padding

This commit is contained in:
2024-12-12 19:11:01 +01:00
parent 1d068b2655
commit de6fe4991c
3 changed files with 29 additions and 9 deletions

View File

@@ -4,6 +4,9 @@ import (
"bytes"
"context"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"log"
"slices"
@@ -17,7 +20,7 @@ import (
)
type BarcodeService interface {
GenerateBarcode(format string, content string, width int, height int) (bytes.Buffer, error)
GenerateBarcode(format string, content string, width int, height int, padding int) (bytes.Buffer, error)
IsTypeSupported(format string) bool
}
@@ -25,7 +28,7 @@ type DefaultBarcodeService struct {
RedisClient *redis.Client
}
func (b *DefaultBarcodeService) GenerateBarcode(format string, content string, width int, height int) (bytes.Buffer, error) {
func (b *DefaultBarcodeService) GenerateBarcode(format string, content string, width int, height int, padding int) (bytes.Buffer, error) {
ctx := context.Background()
if !b.IsTypeSupported(format) {
@@ -71,8 +74,16 @@ func (b *DefaultBarcodeService) GenerateBarcode(format string, content string, w
return bytes.Buffer{}, err
}
// Create a white background image
bg := image.NewRGBA(image.Rect(0, 0, width+2*padding, height+2*padding))
white := color.RGBA{255, 255, 255, 255}
draw.Draw(bg, bg.Bounds(), &image.Uniform{white}, image.Point{}, draw.Src)
// Draw the barcode on top of the white background with padding
draw.Draw(bg, scaledCode.Bounds().Add(image.Point{padding + (width-scaledCode.Bounds().Dx())/2, padding + (height-scaledCode.Bounds().Dy())/2}), scaledCode, image.Point{}, draw.Over)
var buf bytes.Buffer
err = png.Encode(&buf, scaledCode)
err = png.Encode(&buf, bg)
if err != nil {
return bytes.Buffer{}, err
}

View File

@@ -42,7 +42,7 @@ func (t *DefaultTemplater) GenerateBarcode(code string, format string, prefix st
}
}
buf, err := t.BarcodeService.GenerateBarcode(format, code, 1000, 500)
buf, err := t.BarcodeService.GenerateBarcode(format, code, 1000, 500, 0)
return base64.StdEncoding.EncodeToString(buf.Bytes()), err
}