用excel合成图像

该博客介绍了如何利用Python的Pillow库读取图像,并通过openpyxl库将图像的RGB色值转换为十六进制色值,进而填充到Excel单元格中,实现图像到Excel的视觉转换。通过定义rgb_to_hex函数进行颜色转换,然后遍历图像像素,逐行填充到Excel工作表中,最后调整单元格的尺寸以适应图像大小。
摘要由CSDN通过智能技术生成

读取图像 \ggPillow 库 操作Excel\ggopenpyxl 库


$ pip3 install openpyxl
$ pip3 install Pillow

从图片读取的像素块色值是 RGB 值,而 openpyxl 向 Excel cell 内填充颜色是十六进制色值,因此咱们先写一个 RGB 和十六进制色值转换的一个函数。

def rgb_to_hex(rgb):
    rgb = rgb.split(',')
    color = ''
    for i in RGB:
        num = int(i)
        color += str(hex(num))[-2:].replace('x', '0').upper()
    return color

图片转换

有了色值转换函数,接下来要做的操作就是逐行读取图片的 RGB 色值,之后将 RGB 色值转换为十六进制色值填充到 Excel 的 cell 中即可

def img2excel(img_path, excel_path):
    img_src = Image.open(img_path)
    # 图片宽高
    img_width = img_src.size[0]
    img_height = img_src.size[1]

    str_strlist = img_src.load()
    wb = openpyxl.Workbook()
    wb.save(excel_path)
    wb = openpyxl.load_workbook(excel_path)
    cell_width, cell_height = 1.0, 1.0

    sheet = wb["Sheet"]
    for w in range(img_width):
        for h in range(img_height):
            data = str_strlist[w, h]
            color = str(data).replace("(", "").replace(")", "")
            color = rgb_to_hex(color)
            # 设置填充颜色为 color
            fille = PatternFill("solid", fgColor=color)
            sheet.cell(h + 1, w + 1).fill = fille
    for i in range(1, sheet.max_row + 1):
        sheet.row_dimensions[i].height = cell_height
    for i in range(1, sheet.max_column + 1):
        sheet.column_dimensions[get_column_letter(i)].width = cell_width
    wb.save(excel_path)
    img_src.close()

 if __name__ == '__main__':
    img_path = '/Users/xyz/Documents/tmp/03.png'
    excel_path = '/Users/xyz/Documents/tmp/3.xlsx'
    img2excel(img_path, excel_path)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值