P20 - Excel_案例_用Excel画画 - 图1 P20 - Excel_案例_用Excel画画 - 图2 P20 - Excel_案例_用Excel画画 - 图3 P20 - Excel_案例_用Excel画画 - 图4

你好,我是UP:法学院毕业的Python程序员兆锋(点击查看🏆近期的付费答疑记录)
如有学习问题,欢迎加入学习群和我交流❤交流群

下面是本讲课程的视频、代码和配套文档:

主要内容

视频内容

点击下方链接,直达本讲视频
点击查看【bilibili】

本讲代码

  1. # coding: utf-8
  2. from PIL import Image
  3. from xlsxwriter.workbook import Workbook
  4. class ExcelPicture(object):
  5. FORMAT_CONSTRAINT = 65536
  6. def __init__(self, pic_file, ratio=0.5):
  7. self.__pic_file = pic_file
  8. self.__ratio = ratio
  9. self.__zoomed_out = False
  10. self.__formats = dict()
  11. # 缩小图片
  12. def zoom_out(self, _img):
  13. _size = _img.size
  14. _img.thumbnail((int(_img.size[0] * self.__ratio), int(_img.size[1] * self.__ratio)))
  15. self.__zoomed_out = True
  16. # 对颜色进行圆整
  17. def round_rgb(self, rgb, model):
  18. return tuple([int(round(x / model) * model) for x in rgb])
  19. # 查找颜色样式,去重
  20. def get_format(self, color):
  21. _format = self.__formats.get(color, None)
  22. if _format is None:
  23. _format = self.__wb.add_format({'bg_color': color})
  24. self.__formats[color] = _format
  25. return _format
  26. # 操作流程
  27. def process(self, output_file='_pic.xlsx', color_rounding=False, color_rounding_model=5.0):
  28. # 创建xlsx文件,并调整行列属性
  29. self.__wb = Workbook(output_file)
  30. self.__sht = self.__wb.add_worksheet()
  31. self.__sht.set_default_row(height=9)
  32. self.__sht.set_column(0, 5000, width=1)
  33. # 打开需要进行转换的图片
  34. _img = Image.open(self.__pic_file)
  35. print ('Picture filename:', self.__pic_file)
  36. # 判断是否需要缩小图片尺寸
  37. if self.__ratio < 1:
  38. self.zoom_out(_img)
  39. # 遍历每一个像素点,并填充对应的颜色到对应的Excel单元格
  40. _size = _img.size
  41. print('Picture size:', _size)
  42. for (x, y) in [(x, y) for x in range(_size[0]) for y in range(_size[1])]:
  43. _clr = _img.getpixel((x, y))
  44. # 如果颜色种类过多,则需要将颜色圆整到近似的颜色上,以减少颜色种类
  45. if color_rounding: _clr = self.round_rgb(_clr, color_rounding_model)
  46. _color = '#%02X%02X%02X' % _clr
  47. self.__sht.write(y, x, '', self.get_format(_color))
  48. self.__wb.close()
  49. # 检查颜色样式种类是否超出限制,Excel2007对样式数量有最大限制
  50. format_size = len(self.__formats.keys())
  51. if format_size >= ExcelPicture.FORMAT_CONSTRAINT:
  52. print('Failed! Color size overflow: %s.' % format_size)
  53. else:
  54. print ('Success!')
  55. print ('Color: %s' % format_size)
  56. print ('Color_rounding:', color_rounding)
  57. if color_rounding:
  58. print ('Color_rounding_model:', color_rounding_model)
  59. if __name__ == '__main__':
  60. r = ExcelPicture('111.jpg', ratio=0.5)
  61. r.process('0407.xlsx', color_rounding=True, color_rounding_model=5.0)

配套文档

111.jpg0407.xlsx

拓展内容

提问与答疑

提供以下3种交流方式:

  • 有任何问题,请加入Python学习群,和我交流~❤交流群
  • 也期待加我好友,我们深入沟通,我的微信:hdylw1024,请务必注明来意,否则很难通过。
  • 或者你也可以直接在本文档的留言板留言,和大家一起讨论~