圖片轉HTML字符畫

 一段很有意思的腳本,把圖片轉字符畫用html展示出來!

import os
from io import BytesIO
from urllib import request

from PIL import Image
from PIL import ImageFilter

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>
'''


def read_into_buffer(filename):
    buf = bytearray(os.path.getsize(filename))
    with open(filename, 'rb') as f:
        f.readinto(buf)
    f.close()
    return buf


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):
        r = request.urlopen(url)
        s = r.read()
        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

    # 生成html文檔
    def buildDOCLocal(self, url, output):
        try:
            binary = read_into_buffer(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


conv = Converter('WPP', 120)

url = 'https://images2015.cnblogs.com/blog/875028/201705/875028-20170503182400351-1841602368.jpg'
out = 'indexs.html'

conv.buildDOC(url, out)


url = 'TIM圖片20200609152027.jpg'
out = 'indexs2.html'
conv.buildDOCLocal(url, out)

效果如圖所示,分網絡圖片和本地圖片兩種方式!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章