Python语言实现将图片转化为html页面


Posted in Python onDecember 06, 2017

PIL 图像处理库

PIL(Python Imaging Library) 是 Python 平台的图像处理标准库。不过 PIL 暂不支持 Python3,可以用 Pillow 代替,API是相同的。

安装 PIL 库

如果你安装了 pip 的话可以直接输入 pip install PIL 命令安装 Pillow。

或者在 PyCharm 中打开 [File] >> [settings] >> [project github] >> [project interpreter] 添加标准库:

Python语言实现将图片转化为html页面

↑ 搜索 Pillow 包,选中 Pillow,点击 Install Package 安装

PIL 使用方法

from PIL import Image

img = Image.open('source.jpg') # 打开图片
width, height = img.size # 图片尺寸

img.thumbnail((width / 2, height / 2)) # 缩略图
img = img.crop((0, 0, width / 2, width / 2)) # 图片裁剪
img = img.convert(mode='L') # 图片转换
img = img.rotate(180) # 图片旋转
img.save('output.jpg') # 保存图片

↑ PIL 常用模块:Image, ImageFilter, ImageDraw, ImageFont, ImageEnhance, ImageFilter...

图片处理过程

图片转换成网页的过程,可以分成五个步骤。首先要选择一个合适的HTML模板,控制好字体的大小和字符间的间距。

然后通过 Python 的 网络访问模块,根据URL获取图片。接着使用 PIL 模块载入二进制图片,将图片压缩到合适的尺寸。

遍历图片的每一个像素,得到该像素的颜色值,应用到HTML的标签上。最后把字符串信息输出到文件中,生成HTML文档。

定制模板

TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>{title}</title>
  <style>
    body {{
      line-height: 1em;
      letter-spacing: 0;
      font-size: 0.6rem;
      background: black;
      text-align: center;
    }}
  </style>
</head>
<body>
  {body}
</body>
</html>
'''

↑ 大括号代表一个占位符,最后会被替换成实际内容,双大括号中的内容则不会被替换。

获取图片

from urllib import request
url = 'https://pic.cnblogs.com/avatar/875028/20160405220401.png'
binary = request.urlopen(url).read()

↑ 通过 URL 得到 byte 数组形式的图片。

处理图片

from PIL import Image
from io import BytesIO
img = Image.open(BytesIO(binary))
img.thumbnail((100, 100)) # 图片压缩

↑ byte 类型的 图片需要通过 BytesIO 转换为 string 类型,才能被 PIL 处理。

生成HTML

piexl = img.load() # 获取像素信息
width, height = img.size # 获取图像尺寸
body, word = '', '博客园'
font = '<font color="{color}">{word}</font>'
for y in range(height):
  for x in range(width):
    r, g, b = piexl[x, y] # 获取像素RGB值
    body += font.format(
      color='#{:02x}{:02x}{:02x}'.format(r, g, b),
      word=word[((y * width + x) % len(word))]
    )
  body += '\n<br />\n'

↑ 使用<font>标签包裹文字,并根据相应像素的RGB值,设置<font>标签的color属性。

导出网页

html = TEMPLATE.format(title=word, body=body)
fo = open('index.html', 'w', encoding='utf8')
fo.write(html)
fo.close()

↑向HTML模板中填充处理完成的数据,使用文件流将字符串以utf8格式输出到文档。

img2html

wo把上面五个步骤封装了起来,这样一来就可以很方便的调用了。

from io import BytesIO
from PIL import Image
from PIL import ImageFilter
from urllib import request

TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>{title}</title>
  <style>
    body {{
      line-height: 1em;
      letter-spacing: 0;
      font-size: 0.6rem;
      background: black;
      text-align: center;
      min-width: {size}em;
    }}
  </style>
</head>
<body>
  {body}
</body>
</html>
'''
class Converter(object):
  def __init__(self, word='田', size=100):
    self.word, self.size = word, size
    self.font = '<font color="{color}">{word}</font>'

  # 读取url内容
  def __network(self, url):
    return request.urlopen(url).read()

  # 处理图片信息
  def __handle(self, binary):
    img = Image.open(BytesIO(binary)) # 打开制图片
    img.thumbnail((self.size, self.size)) # 压缩图片
    img.filter(ImageFilter.DETAIL) # 图片增强
    return img

  # 分析图片像素
  def __analysis(self, img):
    body = ''
    piexls = img.load()
    width, height = img.size
    for y in range(height):
      for x in range(width):
        r, g, b = piexls[x, y]
        body += self.font.format(
          color='#{:02x}{:02x}{:02x}'.format(r, g, b),
          word=self.word[((y * width + x) % len(self.word))]
        )
      body += '\n<br />\n'
    return body
  # 写入文件内容
  def __writefile(self, file, str):
    fo = open(file, 'w', encoding='utf8')
    try:
      fo.write(str)
    except IOError:
      raise Exception
    finally:
      fo.close()

  # 生成html文档
  def buildDOC(self, url, output):
    try:
      binary = self.__network(url)
      img = self.__handle(binary)
      html = TEMPLATE.format(
        title=self.word,
        body=self.__analysis(img),
        size=self.size
      ) # 向模板中填充数据
      self.__writefile(output, html)
    except Exception as err:
      print('Error:', err)
      return False
    else:
      print('Successful!')
      return True

导入 img2html.Converter,调用 buildDOC(url, out) 方法

from img2html import Converter
conv = Converter('卷福', 120)
url = 'http://www.sznews.com/ent/images/attachement/jpg/site3/20140215/001e4f9d7bf91469078115.jpg'
out = 'index.html'
conv.buildDOC(url, out)

↑ 程序会在当前目录生成 index.html 文件,需要用浏览器打开后才可以看到效果。

转换效果

原始图片 输出HTML

总结

以上就是本文关于Python实现将图片转化为html页面的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
centos下更新Python版本的步骤
Feb 12 Python
Python判断值是否在list或set中的性能对比分析
Apr 16 Python
Python中使用多进程来实现并行处理的方法小结
Aug 09 Python
详解Python核心对象类型字符串
Feb 11 Python
influx+grafana自定义python采集数据和一些坑的总结
Sep 17 Python
使用Python将Mysql的查询数据导出到文件的方法
Feb 25 Python
Python实现二叉树的常见遍历操作总结【7种方法】
Mar 06 Python
python numpy存取文件的方式
Apr 01 Python
Python填充任意颜色,不同算法时间差异分析说明
May 16 Python
利用python对excel中一列的时间数据更改格式操作
Jul 14 Python
python的setattr函数实例用法
Dec 16 Python
LyScript实现绕过反调试保护的示例详解
Aug 14 Python
Python实现比较扑克牌大小程序代码示例
Dec 06 #Python
Python3简单实例计算同花的概率代码
Dec 06 #Python
Python基于回溯法解决01背包问题实例
Dec 06 #Python
Python基于动态规划算法解决01背包问题实例
Dec 06 #Python
Python机器学习之决策树算法实例详解
Dec 06 #Python
快速入门python学习笔记
Dec 06 #Python
Python中django学习心得
Dec 06 #Python
You might like
建立动态的WML站点(三)
2006/10/09 PHP
CI(CodeIgniter)框架中的增删改查操作
2014/06/10 PHP
如何让PHP编码更加好看利于阅读
2019/05/12 PHP
PHP实现基本留言板功能原理与步骤详解
2020/03/26 PHP
Node.js开发之访问Redis数据库教程
2015/01/14 Javascript
jQuery判断多个input file 都不能为空的例子
2015/06/23 Javascript
jquery分页插件jquery.pagination.js使用方法解析
2016/04/01 Javascript
jQuery使用each方法与for语句遍历数组示例
2016/06/16 Javascript
Angular外部使用js调用Angular控制器中的函数方法或变量用法示例
2016/08/05 Javascript
总结AngularJS开发者最常犯的十个错误
2016/08/31 Javascript
JS 学习总结之正则表达式的懒惰性和贪婪性
2017/07/03 Javascript
select自定义小三角样式代码(实用总结)
2017/08/18 Javascript
elementUI select组件默认选中效果实现的方法
2019/03/25 Javascript
详解滑动穿透(锁body)终极探索
2019/04/16 Javascript
javascript实现获取中文汉字拼音首字母
2020/05/19 Javascript
Vue之封装公用变量以及实现方式
2020/07/31 Javascript
Vue 实现对quill-editor组件中的工具栏添加title
2020/08/03 Javascript
[03:01]完美盛典趣味短片 DOTA2年度最佳&拉胯英雄
2019/12/07 DOTA
[39:21]LGD vs OG 2019国际邀请赛淘汰赛 胜者组 BO3 第二场 8.24
2019/09/10 DOTA
仅利用30行Python代码来展示X算法
2015/04/01 Python
Python中super函数的用法
2017/11/17 Python
Python字典遍历操作实例小结
2019/03/05 Python
python GUI库图形界面开发之PyQt5中QWebEngineView内嵌网页与Python的数据交互传参详细方法实例
2020/02/26 Python
Python3爬虫mitmproxy的安装步骤
2020/07/29 Python
CSS3中background-clip和background-origin的区别示例介绍
2014/03/10 HTML / CSS
Lookfantastic葡萄牙官方网站:欧洲第一大化妆品零售商
2018/03/17 全球购物
菲律宾票务网站:StubHub菲律宾
2018/04/21 全球购物
LN-CC日本:高端男装和女装的奢侈时尚目的地
2019/09/01 全球购物
机械设计职业生涯规划书
2013/12/27 职场文书
成品仓管员工作职责
2013/12/29 职场文书
公司道歉信范文
2014/01/09 职场文书
大学迎新晚会主持词
2014/03/24 职场文书
汽修专业自荐信
2014/07/07 职场文书
怎样写离婚协议书
2014/09/10 职场文书
2016年“12.4”法制宣传日活动总结
2016/04/01 职场文书
经典法律座右铭(50句)
2019/08/15 职场文书