barcode
barcode copied to clipboard
Support Fractional Scaling in 2D Barcodes
Add support for fractional scaling to the barcode.Scale function for 2D barcodes.
Take the following example code:
package main
import (
"fmt"
"image"
"image/png"
"os"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/pdf417"
)
func main() {
originalBarcode, _ := pdf417.Encode(`abcdefghijklmnopqrstuvwxyz0123456789`, 4)
writeImage("scaled_1x.png", originalBarcode)
originalBarcodeWidth := originalBarcode.Bounds().Max.X
originalBarcodeHeight := originalBarcode.Bounds().Max.Y
scaled2x, _ := barcode.Scale(originalBarcode, originalBarcodeWidth*2, originalBarcodeHeight*2)
writeImage("scaled_2x.png", scaled2x)
scaled3x, _ := barcode.Scale(originalBarcode, originalBarcodeWidth*3, originalBarcodeHeight*3)
writeImage("scaled_3x.png", scaled3x)
scaled2_5x, _ := barcode.Scale(originalBarcode, int(float64(originalBarcodeWidth)*2.5), int(float64(originalBarcodeHeight)*2.5))
writeImage("scaled_2_5x.png", scaled2_5x)
scaled_409x82, _ := barcode.Scale(originalBarcode, 409, 82)
writeImage("scaled_409_82.png", scaled_409x82)
}
func writeImage(filepath string, i image.Image) {
file, err := os.Create(filepath)
if err != nil {
panic(fmt.Errorf("could not create file %s: %w", filepath, err))
}
defer file.Close()
err = png.Encode(file, i)
if err != nil {
panic(fmt.Errorf("could not save image to file %s: %w", filepath, err))
}
}
Expectation: The scaled barcode image is as large as possible within the defined image size while maintaining the aspect ratio of the barcode. If the aspect ratio of the barcode makes it to where the specified dimension cannot be honored, then scale up the barcode as much as possible and add padding in the horizontal or vertical direction and center the barcode.
Reality: The barcode's scale factor is rounded down to the nearest whole number. Using the above example, here is the image output:
scaled_1x.png
scaled_2x.png
scaled_3x.png
scaled_2_5x.png
scaled_409_82.png