import base64
import io
import os

from PIL import Image

try:
    from pyzbar.pyzbar import decode
except:
    pass
from scrapy.core.scraper import logger


def show_image(image_bytes):
    image_io = io.BytesIO(image_bytes)
    image = Image.open(image_io)
    image.show()


def bytes_image_to_base64(image_bytes):
    image_base64 = base64.b64encode(image_bytes).decode('utf-8')
    return image_base64


def filter_image(image_store, img, item):
    img_abs_path = os.path.join(image_store, img['path'])
    img_url = img["url"]
    # 过滤已存在于自定义过滤列表中的图片
    if 'custom_image_filter' in item and any(custom in img_url for custom in item['custom_image_filter']):
        logger.info(f'公众号[{item["es_urltitle"]}]的图片已在自定义过滤列表中，已过滤--图片url:{img_url}')
        return True, img_url
    if not ('image_min_width' in item and 'image_min_height' in item):
        return False, img_abs_path
    # 过滤指定分辨率和包含二维码的图片
    try:
        image = Image.open(img_abs_path)
    except:
        logger.error(
            f'公众号[{item["es_urltitle"]}]的图片无法打开，已过滤--图片url:{img_url}')
        return True, img_url
    width, height = image.size
    if width < int(item['image_min_width']) or height < int(item['image_min_height']):
        logger.info(f"图片分辨率过小，已过滤，图片Url：{img_url}")
        return True, img_url
    if decode(image):
        logger.info(f"识别到二维码图片，已过滤，图片Url：{img_url}")
        return True, img_url
    return False, img_abs_path
