fix composition

This commit is contained in:
Piotr Oleszczyk 2025-06-18 15:12:57 +02:00
parent 33906be0cf
commit 17e6219140

33
app.py
View file

@ -32,7 +32,7 @@ def make_code128(data: str) -> Image.Image:
"module_width": 0.5, # bar thickness "module_width": 0.5, # bar thickness
"quiet_zone": 1.0, # margin on each side "quiet_zone": 1.0, # margin on each side
"font_size": 10, # text size "font_size": 10, # text size
"text_distance": 1.0, # gap between bars and text "text_distance": 5.0, # gap between bars and text
# you can also pass 'format': 'PNG' here if needed # you can also pass 'format': 'PNG' here if needed
}, },
text=data, # explicitly draw your data string under the bars text=data, # explicitly draw your data string under the bars
@ -59,15 +59,36 @@ class PrintRequest(BaseModel):
def compose_label(images: List[Image.Image]) -> Image.Image: def compose_label(images: List[Image.Image]) -> Image.Image:
"""
Horizontally stack each barcode image with padding,
first scaling them all to the same height.
"""
border, spacing = 10, 20 border, spacing = 10, 20
framed = [ImageOps.expand(img, border=border, fill="white") for img in images]
max_h = max(img.height for img in framed)
total_w = sum(img.width for img in framed) + spacing * (len(framed) - 1)
canvas = Image.new("1", (total_w, max_h), 1) # 1) Determine target inner height (max of original heights)
inner_h = max(img.height for img in images)
# 2) Scale each image to inner_h, then frame it
framed = []
for img in images:
w, h = img.size
new_w = int(w * inner_h / h)
# high-quality up-scaling
img_scaled = img.resize((new_w, inner_h), Image.LANCZOS)
# add white border
framed_img = ImageOps.expand(img_scaled, border=border, fill="white")
framed.append(framed_img)
# 3) Compute final canvas size
total_w = sum(img.width for img in framed) + spacing * (len(framed) - 1)
final_h = inner_h + 2 * border
# 4) Create canvas and paste each framed image
canvas = Image.new("1", (total_w, final_h), 1)
x = 0 x = 0
for img in framed: for img in framed:
y = (max_h - img.height) // 2 # vertical center (though theyre all same height now)
y = (final_h - img.height) // 2
canvas.paste(img, (x, y)) canvas.paste(img, (x, y))
x += img.width + spacing x += img.width + spacing