欢迎访问宙启技术站
智能推送

如何使用Python编写一个简单的图片处理程序

发布时间:2023-12-04 16:49:25

使用Python编写图片处理程序可以使用PIL库(Python Imaging Library),它是Python中常用的图像处理库。以下是一个简单的图片处理程序的示例代码。

from PIL import Image, ImageFilter

def load_image(image_path):
    """
    加载图片
    """
    try:
        image = Image.open(image_path)
        return image
    except FileNotFoundError:
        print("找不到图片文件!")
        return None

def save_image(image, save_path):
    """
    保存图片
    """
    try:
        image.save(save_path)
        print(f"图片已保存为 {save_path}")
    except:
        print("保存图片时出错!")

def resize_image(image, width=None, height=None):
    """
    调整图片尺寸
    """
    if not width and not height:
        return image

    if width and height:
        return image.resize((width, height))
    elif width:
        ratio = width / image.width
        height = int(image.height * ratio)
        return image.resize((width, height))
    elif height:
        ratio = height / image.height
        width = int(image.width * ratio)
        return image.resize((width, height))

def apply_filter(image, filter_type):
    """
    应用滤镜
    """
    if filter_type == "BLUR":
        return image.filter(ImageFilter.BLUR)
    elif filter_type == "CONTOUR":
        return image.filter(ImageFilter.CONTOUR)
    elif filter_type == "DETAIL":
        return image.filter(ImageFilter.DETAIL)
    elif filter_type == "EDGE_ENHANCE":
        return image.filter(ImageFilter.EDGE_ENHANCE)
    elif filter_type == "EMBOSS":
        return image.filter(ImageFilter.EMBOSS)
    elif filter_type == "SHARPEN":
        return image.filter(ImageFilter.SHARPEN)
    else:
        return image

def main():
    image_path = "input.jpg"
    save_path = "output.jpg"

    # 加载图片
    image = load_image(image_path)
    if not image:
        exit()

    # 调整图片尺寸
    image = resize_image(image, width=500)

    # 应用滤镜
    image = apply_filter(image, filter_type="BLUR")

    # 保存图片
    save_image(image, save_path)

if __name__ == "__main__":
    main()

上述代码中,首先通过load_image函数加载图片,如果图片文件不存在,则会打印错误信息。然后,通过resize_image函数可以调整图片的尺寸,可以指定新的宽度和高度,或者同时指定宽度和高度。接下来,通过apply_filter函数可以应用不同的滤镜效果,例如模糊、轮廓、细节增强等。最后,通过save_image函数保存处理后的图片,可以指定保存的路径。

main函数中,我们可以根据需要来加载图片、调整图片尺寸、应用滤镜,并最后保存处理后的图片。上述示例代码中的示例操作为加载一张名为input.jpg的图片,将其尺寸调整为宽度为500,并应用了BLUR(模糊)滤镜效果,最后将处理后的图片保存为output.jpg

当然,以上只是一个简单的示例程序,你可以根据具体需求进行进一步的开发和扩展。