摸鱼 | 图片转Excel单元格脚本

依赖安装

python 复制代码
pip install Pillow tqdm

源码:

python 复制代码
import argparse
from PIL import Image
import openpyxl
from openpyxl.styles import PatternFill
from tqdm import tqdm

def image_to_excel(image_path, excel_path, cell_size=20, sample_ratio=1, output_width=None, output_height=None):
    # 打开图片
    img = Image.open(image_path)
    img = img.convert("RGB")  # 确保是RGB模式

    # 计算新尺寸
    new_width = img.width // sample_ratio
    new_height = img.height // sample_ratio

    # 如果指定了宽度或长度,自动计算另一个维度
    if output_width is not None:
        new_height = int(new_width * img.height / img.width)
    elif output_height is not None:
        new_width = int(new_height * img.width / img.height)

    # 创建一个新的Excel工作簿
    wb = openpyxl.Workbook()
    ws = wb.active

    # 设置列宽和行高
    for col in range(new_width):
        ws.column_dimensions[openpyxl.utils.get_column_letter(col + 1)].width = cell_size / 7
    for row in range(new_height):
        ws.row_dimensions[row + 1].height = cell_size

    # 填充单元格并显示进度条
    for y in tqdm(range(new_height), desc="Processing Rows"):
        for x in range(new_width):
            r, g, b = img.getpixel((x * sample_ratio, y * sample_ratio))
            # 创建填充颜色
            fill = PatternFill(start_color=f'{r:02X}{g:02X}{b:02X}', end_color=f'{r:02X}{g:02X}{b:02X}', fill_type='solid')
            ws.cell(row=y + 1, column=x + 1).fill = fill

    # 保存Excel文件
    wb.save(excel_path)
    print(f"\nSuccessfully converted '{image_path}' to '{excel_path}'.")

def main():
    parser = argparse.ArgumentParser(
        description='Convert an image to an Excel file with pixel colors. '
                    'Each pixel in the image will be represented as a colored cell in the Excel file.'
    )
    parser.add_argument('image_path', type=str, help='Path to the input image file (e.g., image.png).')
    parser.add_argument('excel_path', type=str, help='Path to the output Excel file (e.g., output.xlsx).')
    parser.add_argument('--cell_size', type=int, default=20, help='Size of the Excel cells in pixels (default: 20).')
    parser.add_argument('--sample_ratio', type=int, default=1, help='Sampling ratio (default: 1 means no sampling).')
    parser.add_argument('--output_width', type=int, help='Specify the output width (number of columns).')
    parser.add_argument('--output_height', type=int, help='Specify the output height (number of rows).')

    args = parser.parse_args()

    print("Starting the image to Excel conversion...")
    print(f"Input Image Path: {args.image_path}")
    print(f"Output Excel Path: {args.excel_path}")
    print(f"Cell Size: {args.cell_size} pixels")
    print(f"Sampling Ratio: {args.sample_ratio}")
    print(f"Output Width: {args.output_width if args.output_width else 'Not specified'}")
    print(f"Output Height: {args.output_height if args.output_height else 'Not specified'}")
    
    image_to_excel(args.image_path, args.excel_path, args.cell_size, args.sample_ratio, args.output_width, args.output_height)

if __name__ == '__main__':
    main()

执行示例:

图片(干饭.png):

执行效果:

使用说明:将代码报错到文件并以.py结尾命名(假设文件名为 image2xlsx.py)

  • 输入-h参数会给出所有参数提示
  • --sample_ratio 指定图片中多少个像素点,转换成一个单元格。默认是1,转换的单元格和图片像素点一样多。
  • --output_width 指定单元格横向个数(宽),"高"按照图片比例自动生成。
  • --output_height 指定单元格纵向个数(高),"宽"按照图片比例自动生成。
  • -- cell_size 单元格大小
相关推荐
virtaitech11 分钟前
OrionX vGPU 研发测试场景下最佳实践之Jupyter模式
ide·人工智能·python·ai·jupyter·ai算力·ai算力资源池化
Bruce_Liuxiaowei17 分钟前
利用Python在Win10环境下实现拨号上网
开发语言·python·win10·拨号
◎菜澜子30 分钟前
pycharm从VCS获取项目报错unable to access:Recv failure:Connection was reset
ide·python·pycharm
Filotimo_33 分钟前
使用 Anaconda 环境在Jupyter和PyCharm 中进行开发
ide·经验分享·笔记·python·学习·jupyter·pycharm
黑金IT1 小时前
WebSocket vs. Server-Sent Events:选择最适合你的实时数据流技术
网络·python·websocket·网络协议·fastapi
Amo Xiang1 小时前
Python 常用模块(二):json模块
开发语言·python·json
cxylay1 小时前
【python版】示波器输出的csv文件(时间与电压数据)如何转换为频率与幅值【方法③】
开发语言·python·示波器·频谱·csv文件·时域·频域
liangbm31 小时前
数学建模笔记—— 蒙特卡罗法
笔记·python·数学建模·概率论·概率统计·三门问题·蒙特卡罗法
叫我DPT1 小时前
Django——多apps目录情况下的app注册
python·django
q567315232 小时前
Metacritic 网站中的游戏开发者和类型信息爬取
数据库·python·线性代数·游戏·sqlite