File size: 2,694 Bytes
00b2f69 332557d 00b2f69 332557d d87b607 332557d 00b2f69 d87b607 00b2f69 332557d 00b2f69 332557d 00b2f69 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
{
"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
}
|