[Quick .png to .jpg] Batch convert png format images to jpg images

Use background:

When we need pictures in jpg target format, but only have png picture sources, we only need to use the following code to batch convert the png format pictures in the target folder, which is fast and effective, and it is not easy to report errors!


Conversion code:


from PIL import Image
import os

# 定义源文件夹和目标文件夹路径
src_folder = './images_png'
dst_folder = './images_jpg'

# 获取源文件夹中所有PNG图像文件的路径
png_files = [os.path.join(src_folder, f) for f in os.listdir(src_folder) if f.endswith('.png')]

# 批量将PNG图像转换为JPEG图像
for png_file in png_files:
    # 打开PNG图像并转换为RGB模式
    png_img = Image.open(png_file).convert('RGB')
    # 生成JPEG文件的路径和文件名
    jpg_file = os.path.join(dst_folder, os.path.splitext(os.path.basename(png_file))[0] + '.jpg')
    # 保存JPEG图像
    png_img.save(jpg_file)

``

Replacement effect:

Before replacement:
insert image description here

After replacing :
insert image description here

Replaced successfully!

Guess you like

Origin blog.csdn.net/qq_45193872/article/details/129370880