From ea6a4a7080fd30a87bacedf95da0ade535f22d8b Mon Sep 17 00:00:00 2001 From: Nicolai Ort Date: Thu, 12 Dec 2024 19:16:55 +0100 Subject: [PATCH] refactor(barcode): Switch to inclusive padding --- services/barcode.go | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/services/barcode.go b/services/barcode.go index 59a3796..cdcd9d1 100644 --- a/services/barcode.go +++ b/services/barcode.go @@ -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)