阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

使用Python在Excel画画

35次阅读
没有评论

共计 1382 个字符,预计需要花费 4 分钟才能阅读完成。

导读 十字绣大家都知道吧,今天小编带大家来玩个电子版的十字绣。用 Python 读取图片的像素值,然后输出到 Excel 表格中,最终形成一幅像素画,也就是电子版的十字绣了。
准备

既然要读取图片,那就需要用到 Pillow 库,操作 Excel 需要用到 openpyxl 库,先把这两个库安装好。

$ 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)
惊艳时刻

激动的心,颤抖的手,来看下最终效果咋样。
使用 Python 在 Excel 画画

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计1382字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中