天宫鹤

Python按照图片尺寸(毫米mm)调整图片尺寸(像素pixel)

# 按照图片尺寸(毫米mm)调整图片尺寸(像素)
def resize_image_by_mm(input_image_path, output_image_path, width_mm=35, height_mm=49):
    """
    输入参数:
    :param input_image_path:原图片路径
    :param output_image_path:输出图片路径
    :param width_mm:默认2英寸证件照:35mmx49mm
    :param height_mm:默认2英寸证件照:35mmx49mm
    功能:按照图片尺寸(毫米mm)调整图片尺寸(像素)
    """
    input_image_path = Path(input_image_path)
    image = Image.open(input_image_path).convert('RGB')  # 打开图片,并转换为RGB模式(24位位深度)
    image = ImageOps.exif_transpose(image)  # 解析图片的 EXIF 中的方位信息,将图片转正

    # 计算新的宽度和高度(单位:像素)
    width_pixel = int(width_mm / inch_to_mm * dpi)  # 1英寸=25.4毫米
    height_pixel = int(height_mm / inch_to_mm * dpi)

    # 创建新的图片并调整大小
    image = image.resize((width_pixel, height_pixel), Image.Resampling.LANCZOS)

    try:
        image.save(output_image_path, quality=100)  # 保存为4.PNG格式图片
        return output_image_path
    except IOError as e:
        return None

 

posted on 2024-07-18 21:21  GoGrid  阅读(2)  评论(0编辑  收藏  举报

导航