|
25 | 25 | import sys, struct
|
26 | 26 | from PIL import Image
|
27 | 27 |
|
28 |
| -def image2bin(image, output_file): |
29 |
| - print(f"Converting image with dimensions {image.size[0]}x{image.size[1]}...") |
| 28 | +def image2bin(image, output_file, transparency): |
| 29 | + w, h = image.size[0], image.size[1] |
| 30 | + print(f"Converting image with dimensions {w}x{h}...") |
30 | 31 | if output_file.endswith(('.c', '.cpp')):
|
31 | 32 | is_cpp = True
|
| 33 | + row_sp, item_sp = (" ", "") if w >= 480 else (" ", " ") |
| 34 | + row_end, data_end = "\n", "};\n" |
32 | 35 | f = open(output_file, 'wt')
|
33 |
| - f.write("const uint16_t image[%d] = {\n" % (image.size[1] * image.size[0])) |
| 36 | + f.write("const uint16_t image[%d] = {\n" % (h * w)) |
34 | 37 | else:
|
35 | 38 | is_cpp = False
|
| 39 | + row_sp, row_end, data_end = b"", b"", b"" |
36 | 40 | f = open(output_file, 'wb')
|
| 41 | + tcolor, got_tcolor = 0, False |
37 | 42 | pixs = image.load()
|
38 |
| - for y in range(image.size[1]): |
39 |
| - f.write(" ") |
40 |
| - for x in range(image.size[0]): |
| 43 | + for y in range(h): |
| 44 | + f.write(row_sp) |
| 45 | + for x in range(w): |
41 | 46 | R = pixs[x, y][0] >> 3
|
42 | 47 | G = pixs[x, y][1] >> 2
|
43 | 48 | B = pixs[x, y][2] >> 3
|
44 | 49 | rgb = (R << 11) | (G << 5) | B
|
45 |
| - if rgb == 0: rgb = 1 |
| 50 | + if transparency: |
| 51 | + if not got_tcolor: |
| 52 | + got_tcolor = True |
| 53 | + tcolor = rgb # First pixel color is transparent |
| 54 | + if rgb == tcolor: rgb = 1 # "color 1" is transparent |
46 | 55 | if is_cpp:
|
47 |
| - strHex = " 0x{0:04X},".format(rgb) |
| 56 | + strHex = item_sp + "0x{0:04X},".format(rgb) |
48 | 57 | f.write(strHex)
|
49 | 58 | else:
|
50 | 59 | f.write(struct.pack("B", (rgb & 0xFF)))
|
51 | 60 | f.write(struct.pack("B", (rgb >> 8) & 0xFF))
|
52 |
| - if is_cpp: f.write("\n") |
53 |
| - if is_cpp: f.write("};\n") |
| 61 | + f.write(row_end) |
| 62 | + f.write(data_end) |
54 | 63 | f.close()
|
55 | 64 |
|
56 | 65 | if len(sys.argv) <= 2:
|
57 | 66 | print("Utility to export a image in Marlin TFT friendly format.")
|
58 | 67 | print("It will dump a raw bin RGB565 image or create a CPP file with an array of 16 bit image pixels.")
|
59 |
| - print("Usage: gen-tft-image.py INPUT_IMAGE.(png|bmp|jpg) OUTPUT_FILE.(cpp|bin)") |
| 68 | + print("Usage: gen-tft-image.py INPUT_IMAGE.(png|bmp|jpg) OUTPUT_FILE.(cpp|bin) [--transparency]") |
60 | 69 | print("Author: rhapsodyv")
|
61 | 70 | exit(1)
|
62 | 71 |
|
| 72 | +transparency = len(sys.argv) > 3 and sys.argv[3] == "--transparency" |
63 | 73 | output_img = sys.argv[2]
|
64 | 74 | img = Image.open(sys.argv[1])
|
65 |
| -image2bin(img, output_img) |
| 75 | +image2bin(img, output_img, transparency) |
0 commit comments