from PIL import Image
import os
import iodef resize_images_in_directory ( directory, target_size= ( 240 , 240 ) , max_file_size_kb= 500 ) : for filename in os. listdir( directory) : if filename. lower( ) . endswith( ( '.png' , '.jpg' , '.jpeg' ) ) : file_path = os. path. join( directory, filename) with Image. open ( file_path) as img: if img. mode != 'RGB' : img = img. convert( 'RGB' ) img = img. resize( target_size, Image. ANTIALIAS) save_quality = 95 while True : buffer = io. BytesIO( ) img. save( buffer , format = 'JPEG' , quality= save_quality) buffer . seek( 0 ) size_kb = len ( buffer . getvalue( ) ) / 1024 if size_kb <= max_file_size_kb or save_quality <= 10 : break save_quality -= 5 with open ( file_path, 'wb' ) as f: f. write( buffer . getvalue( ) )
resize_images_in_directory( "C:/Users/JJ/Desktop/shousi" )