from PIL import Image


def convert_image3(image_path, width_mm, height_mm, dpi):
    # 打开原始图片
    image = Image.open(image_path)

    # 计算目标像素尺寸
    width_px = int(width_mm / 25.4 * dpi)
    height_px = int(height_mm / 25.4 * dpi)

    # 调整图片尺寸
    resized_image = image.resize((width_px, height_px))

    # 保存调整后的图片
    resized_image.save(r'D:\temp\zcy21ok_3.jpg')
    print('over')


def get_physical_size(image_path):
    # 打开图片
    with Image.open(image_path) as img:
        # 获取像素尺寸
        width, height = img.size

        # 尝试获取DPI信息
        dpi = 300

        # 如果DPI信息存在,则计算物理尺寸
        if dpi:
            # DPI通常是一个元组,包含水平和垂直方向的DPI
            dpi_x, dpi_y = 300, 300

            # 计算物理尺寸(以英寸为单位)
            physical_width_inches = width / dpi_x
            physical_height_inches = height / dpi_y

            # 转换为毫米(1英寸 = 25.4毫米)
            physical_width_mm = physical_width_inches * 25.4
            physical_height_mm = physical_height_inches * 25.4

            return (physical_width_mm, physical_height_mm)
        else:
            # 如果DPI信息不存在,则返回None
            return None


if __name__ == '__main__':
    # 调用函数进行转换,传入参数:图片路径、目标宽度(毫米)、目标高度(毫米)、目标宽度(像素)、目标高度(像素)
    # convert_image(r'D:\temp\zcy21ok.jpg', 35, 49, 413, 579)

    # 调用函数进行转换,传入参数:图片路径、目标宽度(毫米)、目标高度(毫米)、像素密度(dpi)
    convert_image3(r'D:\temp\zcy21ok.jpg', 35, 49, 300)

    # 测试

    image_path = r'D:\temp\zcy21ok_3.jpg'
    print(get_physical_size(image_path))