import io import math import os from datetime import datetime import gradio as gr from PIL import Image APP_TITLE = "Image → ZPL (^GFA) Converter" APP_DESC = """ Upload an image and get Zebra ZPL code using **^GFA (ASCII Hex)**. - Automatically scales to your target label width (inches × DPI). - Choose dithering or a manual threshold, and optionally invert. - Preview the 1-bit image and download a `.zpl` file ready to print. **Tip:** For a 4×6" label at 203 dpi, the max width is about **812 dots** (4×203). """ def _to_monochrome(img: Image.Image, use_dither: bool, threshold: int, invert: bool) -> Image.Image: # Convert to grayscale g = img.convert("L") if use_dither: # Floyd-Steinberg dithering to 1-bit bw = g.convert("1") # default uses Floyd-Steinberg else: # Manual threshold to 1-bit bw = g.point(lambda p: 255 if p >= threshold else 0).convert("1") if invert: # Invert: swap black(0) and white(255) bw = bw.point(lambda p: 255 - p, mode="1") return bw def _scale_to_width(img: Image.Image, target_width_dots: int) -> Image.Image: if target_width_dots <= 0: return img w, h = img.size if w == target_width_dots: return img # Keep aspect ratio new_h = int(round(h * (target_width_dots / float(w)))) return img.resize((target_width_dots, max(new_h, 1)), resample=Image.BICUBIC) def _pad_to_byte_boundary(img_1bit: Image.Image) -> Image.Image: # ZPL ^GFA consumes rows packed 8 pixels per byte; pad width to multiple of 8 with white pixels w, h = img_1bit.size pad = (8 - (w % 8)) % 8 if pad == 0: return img_1bit new_img = Image.new("1", (w + pad, h), 1) # white background new_img.paste(img_1bit, (0, 0)) return new_img def _image_to_gfa_hex(img_1bit: Image.Image) -> tuple[str, int, int, int]: """ Convert a 1-bit Pillow image (mode '1') to ZPL ^GFA ASCII hex. Returns: (hexdata, total_bytes, bytes_per_row, rows) In ZPL, bit=1 is a black dot. In PIL '1', pixel 0 is black, 255 is white. We'll map (pixel==0) -> bit=1. """ w, h = img_1bit.size bytes_per_row = (w + 7) // 8 raw = bytearray() px = img_1bit.load() for y in range(h): byte_val = 0 bit_count = 0 for x in range(w): # PIL '1': 0=black, 255=white is_black = (px[x, y] == 0) byte_val = (byte_val << 1) | (1 if is_black else 0) bit_count += 1 if bit_count == 8: raw.append(byte_val) byte_val = 0 bit_count = 0 if bit_count > 0: # flush remaining bits left-aligned byte_val = byte_val << (8 - bit_count) raw.append(byte_val) hexdata = ''.join(f'{b:02X}' for b in raw) total_bytes = len(raw) rows = h return hexdata, total_bytes, bytes_per_row, rows def convert_to_zpl( image: Image.Image, dpi: int, max_width_inches: float, use_dither: bool, threshold: int, invert: bool, x_offset: int, y_offset: int, add_label_header: bool, add_pw_ll: bool, filename_hint: str ): if image is None: return None, "", None # Compute target width in dots target_width_dots = int(max(1, round(dpi * max_width_inches))) # Convert to 1-bit with options mono = _to_monochrome(image, use_dither=use_dither, threshold=threshold, invert=invert) # Scale then pad scaled = _scale_to_width(mono, target_width_dots=target_width_dots) padded = _pad_to_byte_boundary(scaled) # Convert to ^GFA fields hexdata, total_bytes, bytes_per_row, rows = _image_to_gfa_hex(padded) # Compose ZPL parts = [] if add_label_header: parts.append("^XA") if add_pw_ll: # Page width (^PW) and label length (^LL) in dots — optional but often helpful parts.append(f"^PW{padded.width}") parts.append(f"^LL{padded.height}") # Position parts.append(f"^FO{x_offset},{y_offset}") # ^GFA,m,n,o,data (m=total bytes, n=bytes/row, o=rows) parts.append(f"^GFA,{total_bytes},{bytes_per_row},{rows},{hexdata}") parts.append("^FS") if add_label_header: parts.append("^XZ") zpl = '\n'.join(parts) # Create a downloadable file safe_name = filename_hint.strip() or "image" safe_name = ''.join(c for c in safe_name if c.isalnum() or c in ('-', '_')) or "image" out_path = f"/tmp/{safe_name}.zpl" with open(out_path, "w", encoding="utf-8") as f: f.write(zpl) return padded, zpl, out_path with gr.Blocks(title=APP_TITLE) as demo: gr.Markdown(f"# {APP_TITLE}\n{APP_DESC}") with gr.Row(): with gr.Column(): in_img = gr.Image(type="pil", label="Upload image") dpi = gr.Dropdown([203, 300, 600], value=203, label="Printer DPI") max_w = gr.Slider(0.5, 8.5, value=4.0, step=0.1, label="Max width (inches)") use_dither = gr.Checkbox(value=True, label="Use Floyd–Steinberg dithering") threshold = gr.Slider(0, 255, value=128, step=1, label="Threshold (ignored if dithering)") invert = gr.Checkbox(value=False, label="Invert black/white") x_off = gr.Number(value=0, precision=0, label="X offset (^FO x)") y_off = gr.Number(value=0, precision=0, label="Y offset (^FO y)") add_header = gr.Checkbox(value=True, label="Wrap with ^XA ... ^XZ") add_pw_ll = gr.Checkbox(value=True, label="Include ^PW and ^LL") fname = gr.Textbox(value="image", label="Output filename (no extension)") run = gr.Button("Convert to ZPL") with gr.Column(): preview = gr.Image(label="1-bit preview (scaled & padded)") zpl_out = gr.Code(label="Generated ZPL (^GFA)") download = gr.File(label="Download .zpl") run.click( fn=convert_to_zpl, inputs=[in_img, dpi, max_w, use_dither, threshold, invert, x_off, y_off, add_header, add_pw_ll, fname], outputs=[preview, zpl_out, download], ) if __name__ == "__main__": demo.launch()