Skip to content

Commit

Permalink
Update package with new functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
CommanderRedYT committed Oct 3, 2024
1 parent b725ce3 commit e42ee69
Show file tree
Hide file tree
Showing 8 changed files with 314 additions and 48 deletions.
39 changes: 32 additions & 7 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,24 @@ name: CI
on:
push:
release:
types:
- release
types: [released]
pull_request:

jobs:
Build:
DeprecatedTests:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ['3.7', '3.8', '3.9', '3.10']
python-version: ['3.7', '3.8', '3.9', '3.10', '3.11', '3.12']
name: python-${{ matrix.python-version }}
steps:

- name: Checkout Repository
uses: actions/checkout@v2
uses: actions/checkout@v4

- name: Install python-${{ matrix.python-version }}
uses: actions/setup-python@v2
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}

Expand All @@ -36,8 +35,34 @@ jobs:
cp -r tests/* /tmp/tests
cd /tmp/tests
- name: Perform Tests
- name: Perform deprecated tests
run: |
rgb565-converter -i /tmp/tests/input_info.png -o /tmp/tests/info.cpp
rgb565-converter -i /tmp/tests/info.cpp -o /tmp/tests/output_info.png
diff /tmp/tests/input_info.png /tmp/tests/output_info.png
Test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ['3.7', '3.8', '3.9', '3.10', '3.11', '3.12']
name: python-${{ matrix.python-version }}
steps:

- name: Checkout Repository
uses: actions/checkout@v4

- name: Install python-${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}

- name: Install Package
run: |
python${{ matrix.python-version }} -m pip install -e ./
# unittest
- name: Run unittest
run: |
python${{ matrix.python-version }} -m unittest discover -s tests -v
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,7 @@ venv.bak/
dmypy.json

# Pyre type checker
.pyre/
.pyre/

# Jetbrains
.idea/
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@
A simple script to help converting png files to rgb565 (used in [TFT_eSPI](https://github.com/Bodmer/TFT_eSPI))

## Install

### Archlinux

```bash
# If you use Archlinux, you can install it from the AUR
yay -S python-rgb565-converter
```

### Via Python Packager

```bash
# Then, install the package
pip install rgb565-converter
Expand Down
123 changes: 85 additions & 38 deletions rgb565_converter/converter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/python3
#!/usr/bin/env python3

import argparse
import os
from PIL import Image
Expand All @@ -8,6 +9,27 @@ class Mode(Enum):
CPP = ".cpp"
PNG = ".png"

DEFAULT_CPP_TEMPLATE="""
#include "{name}.h"
namespace {namespace} {{
const espgui::Icon<{width}, {height}> {name}{{{{
{image_content}
}}, "{name}"}};
}} // namespace {namespace}
"""

DEFAULT_H_TEMPLATE="""
#pragma once
// 3rdparty lib includes
#include <icon.h>
namespace {namespace} {{
extern const espgui::Icon<{width}, {height}> {name};
}} // namespace {namespace}
"""

def main():
parser = argparse.ArgumentParser(
description="Convert a file from one format to another."
Expand All @@ -32,8 +54,49 @@ def main():
dest="swap",
help="Swap bytes for 16-bit words."
)
parser.add_argument(
"-n",
"--namespace",
dest="namespace",
help="C++ Namespace prefix for output files.",
default="icons",
type=str
)
parser.add_argument(
"--cpp-template-file",
dest="cpp_template_file",
help="C++ template file for output files.",
default=None,
type=str
)
parser.add_argument(
"--h-template-file",
dest="h_template_file",
help="Header template file for output files.",
default=None,
type=str
)
args = parser.parse_args()

h_template = DEFAULT_H_TEMPLATE
cpp_template = DEFAULT_CPP_TEMPLATE

if args.cpp_template_file is not None:
try:
with open(args.cpp_template_file, 'r') as f:
cpp_template = f.read()
except:
print("Error: Invalid C++ template file.")
exit(1)

if args.h_template_file is not None:
try:
with open(args.h_template_file, 'r') as f:
h_template = f.read()
except:
print("Error: Invalid header template file.")
exit(1)

input_basename = os.path.basename(args.input_file).rsplit('.', 1)

mode = Mode.CPP if (input_basename[1] == 'png') else Mode.PNG
Expand All @@ -47,27 +110,27 @@ def main():
print("Error: Invalid arguments.")
exit(1)

if (input_basename[1] not in ['png', 'cpp']):
if input_basename[1] not in ['png', 'cpp']:
print("Error: Input file must be a .png or .cpp file.")
exit(1)

if (output_basename[1] not in ['png', 'cpp']):
if output_basename[1] not in ['png', 'cpp']:
print("Error: Output file must be a .png or .cpp file.")
print(f"Output file: {output_basename}")
exit(1)

if (input_basename[1] == output_basename[1]):
if input_basename[1] == output_basename[1]:
print("Error: Input and output file must be different.")
exit(1)

if (mode == Mode.PNG):
convert_rgb565_to_png(args)
if mode == Mode.PNG:
convert_rgb565_to_png(args.input_file, args.output_file, args.swap)
else:
convert_png_to_rgb565(args)
convert_png_to_rgb565(args.input_file, args.output_file, args.swap, args.namespace, cpp_template, h_template)

def convert_png_to_rgb565(args):
name = os.path.basename(args.output_file).rsplit('.', 1)[0]
png = Image.open(args.input_file)
def convert_png_to_rgb565(input_file: str, output_file: str, swap: bool, namespace: str, cpp_template: str = DEFAULT_CPP_TEMPLATE, h_template: str = DEFAULT_H_TEMPLATE):
name = os.path.basename(output_file).rsplit('.', 1)[0]
png = Image.open(input_file)
width, height = png.size

max_line_width = min(width, 64)
Expand All @@ -81,45 +144,29 @@ def convert_png_to_rgb565(args):
b = (pixel[2] >> 3) & 0x1F
rgb = r << 11 | g << 5 | b

if args.swap:
if swap:
rgb = ((rgb & 0xFF) << 8) | ((rgb & 0xFF00) >> 8)

image_content += f"0x{rgb:04X}" + (",\n " if (i % max_line_width == max_line_width-1) else ",")

if image_content.endswith("\n "):
image_content = image_content[:-5]

output_h_content = f"""
#pragma once
// 3rdparty lib includes
#include <icon.h>
namespace icons {{
extern const espgui::Icon<{width}, {height}> {name};
}} // namespace icons
""".strip() + "\n"

output_cpp_content = f"""
#include "{name}.h"
output_h_content = h_template.format(namespace=namespace, width=width, height=height, name=name).strip() + "\n"

namespace icons {{
const espgui::Icon<{width}, {height}> {name}{{{{
{image_content}
}}, "{name}"}};
}} // namespace icons
""".strip() + "\n"
output_cpp_content = cpp_template.format(namespace=namespace, width=width, height=height, name=name, image_content=image_content).strip() + "\n"


with open(args.output_file, 'w') as output_file:
output_file.write(output_cpp_content)
with open(output_file, 'w') as f:
f.write(output_cpp_content)

with open(args.output_file.replace('.cpp', '.h'), 'w') as output_file:
output_file.write(output_h_content)
with open(output_file.replace('.cpp', '.h'), 'w') as f:
f.write(output_h_content)


def convert_rgb565_to_png(args):
with open(args.input_file, 'r') as input_file:
tmp = input_file.read()
def convert_rgb565_to_png(input_file: str, output_file: str, swap: bool):
with open(input_file, 'r') as f:
tmp = f.read()
icon_size = tmp.split('espgui::Icon<')[1].split('>')[0].replace(', ', ',').split(',')
tmp = tmp.split('{{')[1].split('}')[0].split('\n')
input_content = ""
Expand All @@ -137,7 +184,7 @@ def convert_rgb565_to_png(args):
b = (int(word, 16)) & 0x1F
png.putpixel((i % width, i // width), (r << 3, g << 2, b << 3))

png.save(args.output_file)
png.save(output_file)

if __name__ == '__main__':
main()
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name='rgb565-converter',
version='1.2.2',
version='1.3.0',
description='Convert a file from png to rgb565 (cpp) and vice versa.',
url='https://github.com/CommanderRedYT/rgb565-converter',
author='CommanderRedYT',
Expand All @@ -18,6 +18,6 @@
long_description_content_type='text/markdown',
install_requires=[
'argparse~=1.4.0',
'Pillow~=8.1.0',
"Pillow==10.0.1",
],
)
11 changes: 11 additions & 0 deletions tests/custom_cpp_template.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#include "{name}.h"

#ifdef TEST

namespace {namespace} {{
const espgui::Icon<{width}, {height}> {name}{{{{
{image_content}
}}, "{name}"}};
}} // namespace {namespace}

#endif
12 changes: 12 additions & 0 deletions tests/custom_h_template.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#pragma once

// 3rdparty lib includes
#include <icon.h>

#ifdef TEST

namespace {namespace} {{
extern const espgui::Icon<{width}, {height}> {name};
}} // namespace {namespace}

#endif
Loading

0 comments on commit e42ee69

Please sign in to comment.