【用python进行图像格式转换】

PillowPython 中一个强大的图像处理库,其截图功能不仅可以获取屏幕截图,还能对截图进行丰富的图像处理操作。例如,您可以使用 Pillow 库对截图进行图像格式转换,如将 JPEG 格式转换为 PNG 格式。

以下为您提供一些使用 Python 进行图像格式转换的代码示例:

首先,使用 Pillow 库进行单一图片格式转换的示例:

import os
from PIL import Image

# 处理一张图片
orginalFile = r'C:\\xxx\\1.webp'  # 源地址
im = Image.open(orginalFile)  # 打开图片
im.load()  # 加载图片
im.save(r'C:\\xxx\\1.jpg')  # 保存为 jpg 格式

其次,使用 Pillow 库进行批量处理文件夹下特定格式图片的示例:

# 批量处理图片格式
class processImage():
    # 一个将批量将 webp 文件转换成 jpg 的程序
    def __init__(self):
        # self.path = r'C:\\Users\\xxx\\1'  # 就一个参数,就是文件夹的位置
        self.path = input('请输入要处理的文件夹路径(绝对路径):')
        self._main()

    # 读取文件夹下的文件
    def loadFile(self):
        fileList = os.listdir(self.path)  # 读取文件夹下的所有文件(包含文件夹)
        return fileList  # 返回列表

    # 查找文件夹下所有 webp 的图像
    def webp2jpg(self, fileList: list):
        for item in fileList:  # 循环读取列表,得到的 item 是文件名
            if item.endswith('.webp'):  # 如果文件名以.webp 结尾
                src = os.path.join(os.path.abspath(self.path), item)  # 获取文件的绝对路径
                print("src=", src)  # 打印看是否符合预期
                im = Image.open(src)  # 绝对路径打开.webp 格式的文件
                im.load()  # 加载
                save_name = src.replace('webp', 'jpg')  # 保存的文件名
                im.save('{}'.format(save_name), 'JPEG')  # 保存
                # os.remove(src)  # 删除源文件。如果想删除源文件,可以将这段代码的注释清除

    # 程序主入口
    def _main(self):
        self.webp2jpg(self.loadFile())

if __name__ == "__main__":
    app = processImage()

另外,还有通用的图像格式转换函数示例:

from PIL import Image

def convert_image_format(input_file, output_file, output_format):
    """ 图片格式转换函数
    :param input_file: 输入图片文件路径
    :param output_file: 输出图片文件路径
    :param output_format: 输出图片格式,如 'JPEG' 或 'PNG'
    """
    # 打开图片
    with Image.open(input_file) as im:
        # 确保图片能正确打开
        im.load()
        # 将图片保存为新的格式
        im.save(output_file, format=output_format)

# 使用示例:
input_filepath = 'path_to_your_input_image.jpg'
output_filepath = 'output_image.png'
convert_image_format(input_filepath, output_filepath, 'PNG')

对于进阶操作,包含质量控制等参数的示例:

from PIL import Image

def advanced_convert_image(input_file, output_file, output_format, quality=95):
    """ 高级图片格式转换函数,包括质量控制等参数
    :param input_file: 输入图片文件路径
    :param output_file: 输出图片文件路径
    :param output_format: 输出图片格式,如 'JPEG' 或 'PNG'
    :param quality: JPEG 图片的质量(仅对 JPEG 格式有效,范围 1 - 100)
    """
    with Image.open(input_file) as im:
        # 对于 JPEG 格式,可以设置图片压缩质量
        options = {}
        if output_format == 'JPEG':
            options['quality'] = quality
        # 保存图片,同时传递额外参数
        im.save(output_file, format=output_format, **options)

# 使用示例:
input_filepath = 'path_to_your_input_image.jpg'
output_filepath = 'output_image_compressed.jpg'
quality_setting = 75  # 设置较低的质量以减小文件体积
advanced_convert_image(input_filepath, output_filepath, 'JPEG', quality=quality_setting)

希望这些代码示例能够帮助您使用 Python 进行图像格式转换。

Pillow库进行单一图片格式转换代码示例

以下是使用Pillow库进行单一图片格式转换的代码示例:

from PIL import Image
# 打开图片文件
img = Image.open('input.jpg')
# 转换图片格式为PNG
img.save('output.png')

在上述代码中,首先使用Image.open()函数打开指定路径的input.jpg图片文件。然后,通过save()方法将其保存为output.png格式。这种方式简单直接,适用于将单个图片从一种格式转换为另一种格式。例如,如果您有一张JPEG格式的风景图片,想要将其转换为PNG格式以保留透明度等特性,就可以使用这段代码。

Pillow库批量处理特定格式图片代码示例

下面是使用Pillow库批量处理特定格式图片的代码示例:

import os
from PIL import Image

def batch_convert_images(folder_path, target_format):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.jpg'):  # 假设处理jpg格式
                file_path = os.path.join(root, file)
                new_filename = os.path.splitext(file) + '.' + target_format
                new_file_path = os.path.join(root, new_filename)
                try:
                    img = Image.open(file_path)
                    img.save(new_file_path, target_format)
                except Exception as e:
                    print(f"处理{file_path}时出错: {e}")

folder_path = 'your_folder_path'
target_format = 'png'
batch_convert_images(folder_path, target_format)

这段代码会遍历指定文件夹及其子文件夹中的所有JPEG格式图片,并将它们转换为指定的格式(这里以PNG为例)。比如,您有一个包含大量JPEG图片的文件夹,想要一次性将它们全部转换为PNG格式,使用这个代码就能高效地完成任务。

通用图像格式转换函数代码示例

以下是一个通用的图像格式转换函数的代码示例:

import cv2

def convert_image_format(input_path, output_path, output_format):
    image = cv2.imread(input_path)
    if image is None:
        print(f"无法读取{input_path}文件")
        return
    cv2.imwrite(output_path, image, [cv2.IMWRITE_JPEG_QUALITY, 100])  # 以JPEG格式为例,可根据需求修改

这个函数能够读取输入路径的图片,并将其以指定格式保存到输出路径。比如,您有一张来自不同来源的图片,无论其原始格式如何,都可以使用这个函数将其转换为您需要的格式。

包含质量控制等参数的图像格式转换代码示例

下面是一个包含质量控制等参数的图像格式转换代码示例:

from PIL import Image

def advanced_convert_image(input_file, output_file, output_format, quality=95):
    # 打开图片
    with Image.open(input_file) as im:
        # 确保图片能正确打开
        im.load()
        # 将图片保存为新的格式,并设置质量参数
        im.save(output_file, format=output_format, quality=quality)

这个函数在进行格式转换时,可以通过设置质量参数来控制输出图片的质量。例如,如果您要将一张高分辨率的图片转换为JPEG格式,但又希望在减小文件大小的同时尽量保持图像质量,就可以通过调整质量参数来达到平衡。

  • 14
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值