{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Convert `.webp` to `.png`\n", "----\n", "\n", "This script converts all WebP images in a specified directory and its subdirectories to PNG format. It utilizes the `os` module to navigate through the directory structure and the `PIL` (Python Imaging Library) module's `Image` class to handle image processing. The function `convert_webp_to_png(directory)` takes a directory path as input, iterates through all files in that directory (including subdirectories), identifies WebP files based on their extension, converts them to PNG format, and saves the converted images in the same location. If conversion is successful, it also removes the original WebP files. If any errors occur during conversion, it prints an error message with details." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Converted C:\\Users\\kade\\Desktop\\training_dir_staging\\1_dharrel\\iee8nodoji731.webp to C:\\Users\\kade\\Desktop\\training_dir_staging\\1_dharrel\\iee8nodoji731.png\n" ] } ], "source": [ "import os\n", "from PIL import Image\n", "\n", "def convert_webp_to_png(directory):\n", " for root, dirs, files in os.walk(directory):\n", " for file in files:\n", " if file.lower().endswith('.webp'):\n", " webp_path = os.path.join(root, file)\n", " png_path = os.path.splitext(webp_path)[0] + '.png'\n", " try:\n", " with Image.open(webp_path) as img:\n", " img.save(png_path, format='PNG')\n", "\n", " os.remove(webp_path)\n", " print(f\"Converted {webp_path} to {png_path}\")\n", " except Exception as e:\n", " print(f\"Error converting {webp_path}: {e}\")\n", "\n", "#directory = r'E:\\training_dir'\n", "directory = r'C:\\Users\\kade\\Desktop\\training_dir_staging'\n", "#directory = r'C:\\Users\\kade\\Desktop\\ayaya'\n", "convert_webp_to_png(directory)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 2 }