chore: move print to printclass

This commit is contained in:
foosinn 2024-03-30 01:22:07 +01:00
parent 69a058834e
commit 934cfba919

View file

@ -25,58 +25,71 @@ def handle_image():
return f"Error loading image: {e}", 500 return f"Error loading image: {e}", 500
try: try:
print_image(img, resize=True) print_image = PrintImage(img)
print_image.print()
except Exception as e: except Exception as e:
return f"Error printing image: {e}", 500 return f"Error printing image: {e}", 500
return "ok", 200 return "ok", 200
def resize_image(img: Image): class PrintImage:
if img.height > img.width: image: Image
img = img.transpose(Image.ROTATE_90)
if 323 / img.width * img.height <= 240: def __init__(self, image: Image, offset=True, resize=True):
img = img.resize(size=(323, int(323 / img.width * img.height))) self.image = image
else: if resize:
img = img.resize(size=(int(240 / img.height * img.width), 240)) self._resize()
return img if offset:
self._offset()
def _resize(self):
img = self.image
def print_image(img: Image, resize=False, offset=True): if img.height > img.width:
img = img.convert("1") img = img.transpose(Image.ROTATE_90)
if resize: if 323 / img.width * img.height <= 240:
img = resize_image(img) img = img.resize(size=(323, int(323 / img.width * img.height)))
if offset: else:
img = img.resize(size=(int(240 / img.height * img.width), 240))
self.image = img
def _offset(self):
imgborder = Image.new("1", (384, 240), color=1) imgborder = Image.new("1", (384, 240), color=1)
imgborder.paste(img, (61, 0)) imgborder.paste(self.image, (61, 0))
img = imgborder self.image = imgborder
buf = [] def print(self):
buf += [0x1B, 0x40] img = self.image.convert("1")
buf += [0x1D, 0x76, 0x30, 0x0]
width = img.width buf = []
height = img.height buf += [0x1B, 0x40]
width8 = width // 8 buf += [0x1D, 0x76, 0x30, 0x0]
buf += [width8 & 0xFF, width8 >> 8] width = img.width
buf += [height & 0xFF, height >> 8] height = img.height
width8 = width // 8
ibuf = [0] * height * width8 buf += [width8 & 0xFF, width8 >> 8]
for y in range(height): buf += [height & 0xFF, height >> 8]
for x in range(width):
if img.getpixel((x, y)) == 0:
ibuf[x // 8 + y * width8] |= 1 << (7 - (x & 7))
ibuf = [b if b != 0x0A else 0x14 for b in ibuf]
buf += ibuf ibuf = [0] * height * width8
for y in range(height):
for x in range(width):
if img.getpixel((x, y)) == 0:
ibuf[x // 8 + y * width8] |= 1 << (7 - (x & 7))
ibuf = [b if b != 0x0A else 0x14 for b in ibuf]
# -- send buf += ibuf
sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) # -- send
sock.bind((socket.BDADDR_ANY, 1))
sock.connect((DEVICE, 1)) sock = socket.socket(
sock.sendall(bytes(buf)) socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM
sock.recv(1024) )
sock.close() sock.bind((socket.BDADDR_ANY, 1))
sock.connect((DEVICE, 1))
sock.sendall(bytes(buf))
sock.recv(1024)
sock.close()