Skip to content

Instantly share code, notes, and snippets.

@prashant3285
Last active November 15, 2024 10:34
Show Gist options
  • Select an option

  • Save prashant3285/5f8b2cad5bd60e84410e9fa2a9d90401 to your computer and use it in GitHub Desktop.

Select an option

Save prashant3285/5f8b2cad5bd60e84410e9fa2a9d90401 to your computer and use it in GitHub Desktop.
Image to AVIF conversion in Python
# pip install pillow
# pip install pillow-avif-plugin
# add image files to Input folder and run the script
# converted files will be stored in output folder
# change folder path at the end of file
import os
from PIL import Image
import glob
import pillow_avif
print("Script Triggered")
def resize_and_convert(input_folder, output_folder):
# Ensure the output folder exists
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Get all image files (png, jpg, jpeg) in the input folder
image_files = glob.glob(os.path.join(input_folder,"*")) # Includes .png, .jpg, .jpeg
# Loop through all image files
for file_path in image_files:
try:
# Open the image
with Image.open(file_path) as img:
# Define the output path (change extension to .avif)
file_name = os.path.splitext(os.path.basename(file_path))[0] + ".avif"
output_path = os.path.join(output_folder, file_name)
# Save the image as AVIF format
img.save(output_path, format="AVIF")
print(f"Converted {file_path} to {output_path}")
except Exception as e:
print(f"Error processing {file_path}: {e}")
if __name__ == "__main__":
input_folder = "C:/Users/Username/Desktop/Input" # Replace with your input folder path
output_folder = "C:/Users/Username/Desktop/Output" # Replace with your output folder path
resize_and_convert(input_folder, output_folder)
# relative path implementation
# dirname = os.path.dirname(__file__)
# input_folder = os.path.join(dirname, 'Input') # Replace with your input folder path
# output_folder = os.path.join(dirname, 'Output') # Replace with your output folder path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment