前言
表格是同盟常见的排版工具。
经过同盟诸多科研人士近10年的科研积累,对于表格的应用似乎已经抵达了极限。
但是,作为高性能的四面体,我要打破这10年的僵局,开创新的领域~
借助脚本的力量,我们可以用表格实现像素级的排版效果~
甚至可以用表格作画,将任何的图片转换成表格~
展示
代码
#!/usr/bin/env python3
"""Convert an image to an HTML table where each cell represents a pixel."""
from PIL import Image
import sys
import os
def image_to_html_table(image_path, output_path, width=120, grayscale=False):
"""Convert an image to an HTML table.
Args:
image_path: Path to the input image
output_path: Path for the output HTML file
width: Target width in cells (height calculated to maintain aspect ratio)
grayscale: If True, convert to grayscale; otherwise use color
"""
# Load the image
img = Image.open(image_path)
# Calculate new height to maintain aspect ratio
aspect_ratio = img.height / img.width
height = int(width * aspect_ratio)
# Resize the image
img = img.resize((width, height), Image.Resampling.LANCZOS)
# Convert to grayscale or RGB
if grayscale:
img = img.convert('L')
else:
img = img.convert('RGB')
# Get pixel data
pixels = list(img.getdata())
# Build HTML
html = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Image - HTML Table</title>
</head>
<body>
<table style="border-collapse:collapse;table-layout:fixed">
"""
# Generate table rows
for y in range(height):
html += " <tr>"
for x in range(width):
if grayscale:
pixel_value = pixels[y * width + x]
hex_color = f"#{pixel_value:02x}{pixel_value:02x}{pixel_value:02x}"
else:
r, g, b = pixels[y * width + x]
hex_color = f"#{r:02x}{g:02x}{b:02x}"
html += f'<td style="background-color:{hex_color};width:6px;height:6px;padding:0;line-height:0"></td>'
html += "</tr>\n"
html += """ </table>
</body>
</html>
"""
# Write output
with open(output_path, 'w') as f:
f.write(html)
print(f"Generated HTML table: {output_path}")
print(f"Dimensions: {width}x{height} cells")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Convert an image to an HTML table")
parser.add_argument("image_path", help="Path to the input image")
parser.add_argument("-w", "--width", type=int, default=120, help="Target width in cells (default: 120)")
parser.add_argument("-g", "--grayscale", action="store_true", help="Convert to grayscale (default: color)")
args = parser.parse_args()
# Derive output path from input filename
base_name = os.path.splitext(os.path.basename(args.image_path))[0]
output_path = f"{base_name}_table.html"
image_to_html_table(args.image_path, output_path, args.width, args.grayscale)
使用方法
只要将以上的代码保存为python脚本,并且提供图片路径直接运行即可~ 比如:
python3 main.py pikachu.jpg
如果需要压缩表格的话,可以通过-w选项指定表格的长度~
python3 main.py pikachu.jpg -w 60
提供--grayscale选项可以生成黑白的表格的说~
python3 main.py pikachu.jpg --grayscale
风险:如果过分使用,saka君可能会开始磨刀的说~