refactor(barcode): Switch to inclusive padding

This commit is contained in:
Nicolai Ort 2024-12-12 19:16:55 +01:00
parent de6fe4991c
commit ea6a4a7080
Signed by: niggl
GPG Key ID: 13AFA55AF62F269F

View File

@ -36,7 +36,7 @@ func (b *DefaultBarcodeService) GenerateBarcode(format string, content string, w
}
if b.RedisClient != nil {
cachedBarcode, err := b.RedisClient.Get(ctx, fmt.Sprintf("barcode:%s:%s:%d:%d", format, content, width, height)).Result()
cachedBarcode, err := b.RedisClient.Get(ctx, fmt.Sprintf("barcode:%s:%s:%d:%d:%d", format, content, width, height, padding)).Result()
if err == nil {
log.Printf("Cache hit for barcode:%s:%s:%d:%d", format, content, width, height)
buf := bytes.Buffer{}
@ -69,18 +69,23 @@ func (b *DefaultBarcodeService) GenerateBarcode(format string, content string, w
break
}
scaledCode, err := barcode.Scale(generatedCode, width, height)
// Create a white background image
bg := image.NewRGBA(image.Rect(0, 0, width, height))
white := color.RGBA{255, 255, 255, 255}
draw.Draw(bg, bg.Bounds(), &image.Uniform{white}, image.Point{}, draw.Src)
// Calculate the new size for the barcode to fit within the padding
newWidth := width - 2*padding
newHeight := height - 2*padding
// Scale the barcode to the new size
scaledCode, err := barcode.Scale(generatedCode, newWidth, newHeight)
if err != nil {
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)
draw.Draw(bg, scaledCode.Bounds().Add(image.Point{padding, padding}), scaledCode, image.Point{}, draw.Over)
var buf bytes.Buffer
err = png.Encode(&buf, bg)