# -*- coding: utf-8 -*-
# 图片相关类
# 作者: 陈磊
# 时间: 2019-10-21


from WorkUtils.UtilsLog import UtilsLog
from WorkBase import WorkBase

import os
import base64
import datetime

from PIL import Image
from PIL import ImageEnhance
from pytesseract import *
from PIL import ImageOps


class UtilsImage:
    def __init__(self):
        self.log = UtilsLog()
        self.log.info("调用图片相关类")
        self.log.info(self.__class__)
        self.create_time = datetime.datetime.today().strftime("%Y%m%d%H%M%S")
        year = str(datetime.datetime.now().year) + u"年"
        month = str(datetime.datetime.now().month) + u"月"
        day = str(datetime.datetime.now().day) + u"日"
        self.img_path = WorkBase().img_path + year + "\\" + month + "\\" + day + "\\"
        self.img_name = ""
        self.img_file = ""
        self.code = ""

    def change_base64(self, bs64):
        self.log.info("获取base64图片内容")
        self.log.info("解析图片...")
        img_file = base64.b64decode(bs64)
        # 将二进制数据装换为图片
        # 生成测试报告文件
        # 更新获取的版本号生成文件
        if os.path.exists(self.img_path):
            pass
        else:
            os.makedirs(self.img_path)

        self.img_name = self.create_time + ".png"
        self.img_file = self.img_path + self.img_name
        with open(self.img_file, "wb") as img_png:
            img_png.write(img_file)
        self.log.info("保存解析的图片")

    def init_table(self, threshold=190):
        self.log.info("二值化阈值:%s" % threshold)
        table = []
        for i in range(256):
            if i < threshold:
                table.append(0)
            else:
                table.append(1)
        return table

    def get_code(self):
        self.log.info("解析图片验证码...")
        # 测试
        self.img_file = "E:\\TestFile\\Img\\2019年\\6月\\19日\\20190619152453.png"
        # 新建Image对象
        image = Image.open(self.img_file)
        # 进行置灰处理
        image = image.convert('L')
        # 这个是二值化阈值
        threshold = 192
        table = []

        for i in range(256):
            if i < threshold:
                table.append(0)
            else:
                table.append(1)
        # 通过表格转换成二进制图片，1的作用是白色，不然就全部黑色了
        image = image.point(table, "1")
        image.show()
        self.code = pytesseract.image_to_string(image, lang="eng")
        self.log.info("验证码:" + self.code)


if __name__ == '__main__':
    i = UtilsImage()
    i.get_code()