From fc3055dcde0eca50046c062dd21e0331a6b749aa Mon Sep 17 00:00:00 2001 From: Thomas Burgess Date: Sat, 12 Oct 2024 00:53:51 -0500 Subject: [PATCH] Added set_image for gfxhat --- gfxhat/lcd.py | 3 +++ gfxhat/st7567.py | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/gfxhat/lcd.py b/gfxhat/lcd.py index 9ba0e4a..f342ea5 100644 --- a/gfxhat/lcd.py +++ b/gfxhat/lcd.py @@ -31,6 +31,9 @@ def contrast(value): """Change GFX HAT LCD contrast.""" st7567.contrast(value) +def set_image(image): + """Set the display buffer from a PIL Image and update the display.""" + st7567.set_image(image) def rotation(r=0): """Set the display rotation. diff --git a/gfxhat/st7567.py b/gfxhat/st7567.py index bf30e17..e5ed4e9 100644 --- a/gfxhat/st7567.py +++ b/gfxhat/st7567.py @@ -181,6 +181,33 @@ def contrast(self, value): self.setup() self._command([ST7567_SETCONTRAST, value]) + def set_image(self, image): + """Set the display buffer from a PIL Image and update the display. + + :param image: PIL Image object to display + + """ + # Ensure the image is in 1-bit mode and correct size + image = image.convert('1').resize((WIDTH, HEIGHT)) + pixels = image.load() + + for y in range(HEIGHT): + for x in range(WIDTH): + pixel = pixels[x, y] + value = 1 if pixel == 1 else 0 + if self.rotated: + x_display = (WIDTH - 1) - x + y_display = (HEIGHT - 1) - y + else: + x_display = x + y_display = y + page = y_display // 8 + bit = y_display % 8 + offset = (page * WIDTH) + x_display + if value: + self.buf[offset] |= (1 << bit) + else: + self.buf[offset] &= ~(1 << bit) if __name__ == '__main__': # pragma: no cover st7567 = ST7567()