Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Fractional Scaling in 2D Barcodes #87

Open
salfonso-easypost opened this issue Oct 17, 2024 · 0 comments
Open

Support Fractional Scaling in 2D Barcodes #87

salfonso-easypost opened this issue Oct 17, 2024 · 0 comments

Comments

@salfonso-easypost
Copy link

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_1x

scaled_2x.png
scaled_2x

scaled_3x.png
scaled_3x

scaled_2_5x.png
scaled_2_5x

scaled_409_82.png
scaled_409_82

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@salfonso-easypost and others