1. Convert images to jpg format in batches
The function of the code is to find non-jpg image files in the specified directory, convert them to jpg format and save them in another directory.
Among them, the PIL module is a third-party image processing library for Python that can be used to read, modify and save files in various image formats. In this code, we use the Image.open() function to open each image file to be converted, and then call the Image.save() function to save it as a jpg format file.
Since there may be differences in pixel density between different image formats, the quality of the image may be affected to a certain extent when converting image formats. If you need to ensure the quality and clarity of the image, please choose the conversion scheme carefully or adjust the image parameters manually.
import os
from PIL import Image
path = "C:/Users/ypzhao/Desktop/pict/"
path_convert = "C:/Users/ypzhao/Desktop/pict_con/"
for i in os.listdir(path):
file_name,file_suffix = i.split(".")
if file_suffix != "jpg":
im = Image.open(path+f"{
i}")
im.save(path_convert+f"{
file_name}"+".jpg")
else:
pass
Before conversion:
After conversion
2. Batch resize images
for i in os.listdir(path_convert):
file_name,file_suffix = i.split(".")
if file_suffix == "jpg":
im = Image.open(path_convert+f"{
i}")
width,height = im.size
print(width,height)
new_width,new_height = int(12*37.8),int(7*37.8)
print(new_width,new_height)
new_im = im.resize((new_width,new_height))
print(new_im.size)
new_im.save(path_resize+f"{
file_name}"+".jpg")
3. Add watermarks to pictures in batches
# -*- coding: utf-8 -*-
"""
Created on Mon May 22 14:33:39 2023
@author: ypzhao
"""
import os
from PIL import Image, ImageDraw, ImageFont
file_path = "C:/Users/ypzhao/Desktop/pict/"
path= "C:/Users/ypzhao/Desktop/resize/"
for i in os.listdir(path):
file_name,file_suffix = i.split(".")
if file_suffix == "jpg":
im = Image.open(path+f"{
i}")
draw = ImageDraw.Draw(im)
font=ImageFont.truetype(r'C:\Windows\Fonts\simhei.ttf',30)
draw.text((200,180),"项目申报小狂人",font=font,fill="yellow")
draw.text((100,80),"项目申报小狂人",font=font,fill="blue")
im.save(file_path+f"{
file_name}"+".jpg")