Last active
December 7, 2021 02:11
-
-
Save otykhonruk/f1fde82225ee0a09e235dc43b02970c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
import os.path | |
from PIL import Image | |
TEMPLATE = """ | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
table.imagetable {{ table-layout: fixed; border:0; border-collapse:collapse; }} | |
table.imagetable tr td {{ padding: 0; width: 1px; height: 1px;}} | |
</style> | |
<title>{title}</title> | |
</head> | |
<body> | |
<table class="imagetable"> | |
<tbody> | |
{table} | |
</tbody> | |
</table> | |
</body> | |
</html> | |
""" | |
def rgb_to_hex(rgb: tuple[int, int, int, int]) -> str: | |
# :3 is too avoid transparency param | |
return '#%02x%02x%02x' % rgb[:3] | |
def get_opacity(pixel: [int, int, int, int]) -> float: | |
if len(pixel) == 3: | |
# no transparency | |
return 1 | |
return round(pixel[3] / 255, 1) | |
def compute_style(pixel: [int, int, int, int], width: int) -> str: | |
style = '' | |
# opacity | |
if len(pixel) > 3: | |
if pixel[3] != 255: | |
opacity = round(pixel[3] / 255, 1) | |
style = f"opacity: {opacity};" | |
if width != 1: | |
style = style + f"width:{width}px;" | |
return f' style="{style}"' if style else '' | |
def gen_td(pixel, counter): | |
html_color = rgb_to_hex(pixel) | |
style = compute_style(pixel, counter) | |
colspan = f' colspan="{counter}"' if counter > 1 else '' | |
return f'<td bgcolor="{html_color}"{style}{colspan}></td>' | |
def gen_table(im): | |
width, height = im.size | |
output = io.StringIO() | |
for y in range(height): | |
output.write('<tr>') | |
same_color_counter = 1 | |
start_pixel = im.getpixel((0, y)) | |
for x in range(1, width + 1): | |
if x == width: | |
output.write(gen_td(start_pixel, same_color_counter)) | |
else: | |
pixel = im.getpixel((x, y)) | |
if pixel != start_pixel: | |
output.write(gen_td(start_pixel, same_color_counter)) | |
same_color_counter = 1 | |
start_pixel = pixel | |
else: | |
same_color_counter += 1 | |
output.write('</tr>') | |
return output.getvalue() | |
def gen_html(image_name): | |
im = Image.open(image_name) | |
table = gen_table(im) | |
name, _ = os.path.splitext(os.path.basename(image_name)) | |
with open(f'{name}.html', 'w') as output: | |
output.write(TEMPLATE.format( | |
title=f'Generated from {image_name}', | |
table=table)) | |
if __name__ == '__main__': | |
from argparse import ArgumentParser | |
parser = ArgumentParser(description='Convert image to HTML table') | |
parser.add_argument('file', | |
help='File path. Can be jpg or png.') | |
args = parser.parse_args() | |
gen_html(args.file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment