# -*- coding:utf-8 -*-
"""图片处理函数"""

from kyger.utility import *
from tools.PIL import ImageDraw, ImageFont, Image, ImageEnhance


class Cropper(object):
    """文章调用"""

    # 构造函数
    def __init__(self, path):
        self.path = path

    def cut(self, width, height):
        """
        图片裁切
        :param width: [int] 裁切的宽度
        :param height: [int] 裁切的高度
        """
        # 获取裁切的配置
        config = json2dict(file='config/set_picture.json')['cut']
        img = Image.open(url_absolute(self.path))

        # 宽高都大于限制才进行裁剪
        if img.size[0] > config['condition'][0] and img.size[1] > config['condition'][1]:
            # 缩放计算
            x = img.size[0] / width
            y = img.size[1] / height
            if x < y:
                img = img.resize((width, int(img.size[1] / x)), Image.ANTIALIAS)
                height_offset = (img.size[1] - height) // 2
                width_offset = 0
            else:
                img = img.resize((int(img.size[0] / y), height), Image.ANTIALIAS)
                width_offset = (img.size[0] - width) // 2
                height_offset = 0
            cropped = img.crop((width_offset, height_offset, width + width_offset, height + height_offset))
            cropped.save(url_absolute(self.path), quality=config['quality'])

    def watermark(self, save_path=''):
        """
        图片水印
        :param save_path: [str] 保存路径
        """
        # 获取水印的配置
        config = json2dict(file='config/set_picture.json')['watermark']

        # 判断是否满足裁切条件
        img = Image.open(url_absolute(self.path))
        if img.size[0] > config['condition'][0] and img.size[1] > config['condition'][1]:

            # 文字水印
            if config['type'] == "word":
                # 水印内容、字体文件、角度、大小
                text, font, angle, size = (config['word'], url_absolute(config['font']), config['angle'], config['size'])

                img = Image.open(url_absolute(self.path)).convert('RGB')
                watermark = Image.new('RGBA', img.size, (0, 0, 0, 0))

                # 获取文字
                n_font = ImageFont.truetype(font, size)
                n_width, n_height = n_font.getsize(text)

                # 图片位置加上偏移
                position = {
                    0: (0 + config['offset'][0], 0 + config['offset'][1]),
                    1: ((watermark.size[0] - n_width) // 2 + config['offset'][0], 0 + config['offset'][1]),
                    2: (watermark.size[0] - n_width + config['offset'][0], 0 + config['offset'][1]),
                    3: (0 + config['offset'][0], (watermark.size[1] - n_height) // 2 + config['offset'][1]),
                    4: ((watermark.size[0] - n_width) // 2 + config['offset'][0], (watermark.size[1] - n_height) // 2 + config['offset'][1]),
                    5: (watermark.size[0] - n_width + config['offset'][0], (watermark.size[1] - n_height) // 2 + config['offset'][1]),
                    6: (0 + config['offset'][0], watermark.size[1] - n_height + config['offset'][1]),
                    7: ((watermark.size[0] - n_width) // 2 + config['offset'][0], watermark.size[1] - n_height + config['offset'][1]),
                    8: (watermark.size[0] - n_width + config['offset'][0], watermark.size[1] - n_height + config['offset'][1]),
                }

                draw = ImageDraw.Draw(watermark, 'RGBA')
                draw.text(position[config['position']], text, font=n_font, fill=config['color'])  # 位置, 内容, 字体, 颜色
                center = (position[config['position']][0] + n_width // 2, position[config['position']][1] + n_height // 2)
                watermark = watermark.rotate(angle, Image.BICUBIC, center=center)  # 旋转角度
                alpha = watermark.split()[3]

                # 通过降低亮度和对比度来降低水印的透明度
                alpha = ImageEnhance.Brightness(alpha).enhance(0.5)

                # 设置透明度
                watermark.putalpha(alpha)

                # 添加水印
                if save_path:
                    Image.composite(watermark, img, watermark).save(url_absolute(save_path))
                else:
                    Image.composite(watermark, img, watermark).save(url_absolute(save_path))

            # 图片水印
            else:
                # 源图、水印图
                image = Image.open(url_absolute(self.path))
                logo = Image.open(url_absolute(config['path']))
                layer = Image.new('RGBA', image.size, (0, 0, 0, 0))

                logo = logo.convert('RGBA')  # 修改颜色通道为RGBA
                x, y = logo.size  # 获得长和宽

                # 设置每个像素点颜色的透明度
                for i in range(x):
                    for k in range(y):
                        color = logo.getpixel((i, k))
                        color = list(color)
                        color[3] = int(color[3] * 0.7)
                        logo.putpixel((i, k), tuple(color))

                # 图片位置加上偏移
                position = {
                    0: (0 + config['offset'][0], 0 + config['offset'][1]),
                    1: ((image.size[0] - logo.size[0]) // 2 + config['offset'][0], 0 + config['offset'][1]),
                    2: (image.size[0] - logo.size[0] + config['offset'][0], 0 + config['offset'][1]),
                    3: (0 + config['offset'][0], (image.size[1] - logo.size[1]) // 2 + config['offset'][1]),
                    4: ((image.size[0] - logo.size[0]) // 2 + config['offset'][0], (image.size[1] - logo.size[1]) // 2 + config['offset'][1]),
                    5: (image.size[0] - logo.size[0] + config['offset'][0], (image.size[1] - logo.size[1]) // 2 + config['offset'][1]),
                    6: (0 + config['offset'][0], image.size[1] - logo.size[1] + config['offset'][1]),
                    7: ((image.size[0] - logo.size[0]) // 2 + config['offset'][0], image.size[1] - logo.size[1] + config['offset'][1]),
                    8: (image.size[0] - logo.size[0] + config['offset'][0], image.size[1] - logo.size[1] + config['offset'][1]),
                }
                layer.paste(logo, position[config['position']])
                out = Image.composite(layer, image, layer)
                if save_path:
                    out.save(url_absolute(save_path), quality=100)
                else:
                    out.save(url_absolute(self.path), quality=100)





