Add automatic label length trimming
This commit is contained in:
+29
@@ -223,6 +223,33 @@ def draw_cutmark(draw: ImageDraw.ImageDraw, width_px: int, height_px: int, scale
|
||||
y += dash + gap
|
||||
|
||||
|
||||
def crop_label_to_content(image: Image.Image, design: dict[str, Any], scale: float) -> Image.Image:
|
||||
if not bool(design.get("autoLength", True)):
|
||||
return image
|
||||
|
||||
tape_width = float(design.get("tapeWidthMm", 24))
|
||||
orientation = design.get("orientation", "landscape")
|
||||
margin_px = scaled_mm_to_px(float(design.get("marginMm", 2)), scale)
|
||||
min_length_px = scaled_mm_to_px(10, scale)
|
||||
black_mask = image.convert("L").point(lambda pixel: 255 if pixel < 128 else 0, "L")
|
||||
bbox = black_mask.getbbox()
|
||||
|
||||
if orientation == "portrait":
|
||||
fixed_width = scaled_mm_to_px(tape_width, scale)
|
||||
if not bbox:
|
||||
return new_label_image(fixed_width, min_length_px)
|
||||
end = min(image.height, bbox[3] + margin_px)
|
||||
target = min(image.height, max(min_length_px, end))
|
||||
return image.crop((0, 0, image.width, target))
|
||||
|
||||
fixed_height = scaled_mm_to_px(tape_width, scale)
|
||||
if not bbox:
|
||||
return new_label_image(min_length_px, fixed_height)
|
||||
end = min(image.width, bbox[2] + margin_px)
|
||||
target = min(image.width, max(min_length_px, end))
|
||||
return image.crop((0, 0, target, image.height))
|
||||
|
||||
|
||||
def render_design_image(design: dict[str, Any]) -> Image.Image:
|
||||
tape_width = float(design.get("tapeWidthMm", 24))
|
||||
if tape_width not in TAPE_WIDTHS_MM:
|
||||
@@ -264,6 +291,8 @@ def render_design_image(design: dict[str, Any]) -> Image.Image:
|
||||
elif obj_type == "barcode":
|
||||
draw_barcode(image, obj, scale)
|
||||
|
||||
image = crop_label_to_content(image, design, scale)
|
||||
draw = ImageDraw.Draw(image)
|
||||
if design.get("cutMode") in {"cutmark", "cutmark-chain"}:
|
||||
draw_cutmark(draw, image.width, image.height, scale)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user