Skip to content

Instantly share code, notes, and snippets.

@parkerlreed
Created June 23, 2025 19:11
Show Gist options
  • Save parkerlreed/f502d06907b485047b8b86783306db29 to your computer and use it in GitHub Desktop.
Save parkerlreed/f502d06907b485047b8b86783306db29 to your computer and use it in GitHub Desktop.
import sys
import bluetooth
from PIL import Image, ImageOps
import numpy as np
import os
def convert_image_to_bitpacked(filepath, width=384, height=390):
# Load the image with RGBA mode to preserve alpha
img = Image.open(filepath).convert("RGBA")
# Flatten onto white background
background = Image.new("RGBA", img.size, (255, 255, 255, 255))
img = Image.alpha_composite(background, img).convert("L")
# Resize to expected printer dimensions
img = img.resize((width, height), Image.Resampling.LANCZOS)
# Convert to 1-bit using standard thresholding without inversion
img_bw = img.point(lambda x: 255 if x < 128 else 0, mode="1")
# Convert to numpy and bitpack
bits = np.array(img_bw, dtype=np.uint8)
packed = np.packbits(bits, axis=1)
return packed.tobytes()
def main(image_path, mac):
# Load original captured binary
if not os.path.exists("print.bin"):
print("Missing 'raw_capture.bin'. Please place it next to this script.")
sys.exit(1)
with open("print.bin", "rb") as f:
raw = f.read()
# Locate GS v 0 m raster command
index = raw.find(b"\x1D\x76\x30\x00")
if index == -1:
print("Raster command not found in raw stream.")
sys.exit(1)
xL, xH = raw[index+4], raw[index+5]
yL, yH = raw[index+6], raw[index+7]
width_bytes = xL + (xH << 8)
height = yL + (yH << 8)
image_size = width_bytes * height
start = index + 8
end = start + image_size
print(f"Image region: offset={start}, size={image_size} bytes")
# Convert and bitpack image
print("Converting image...")
image_data = convert_image_to_bitpacked(image_path, width_bytes * 8, height)
if len(image_data) != image_size:
print(f"Image size mismatch: expected {image_size}, got {len(image_data)}.")
sys.exit(1)
# Splice into raw stream
patched = raw[:start] + image_data + raw[end:]
# Send via Bluetooth
print(f"Connecting to {mac}...")
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((mac, 1))
print("Sending...")
sock.send(patched)
sock.close()
print("Done.")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: replace_and_send_from_hex_fixed.py <image.png> <MAC_ADDRESS>")
sys.exit(1)
main(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment