Code-Parth / WebP-Converter

WebP Converter: A Windows utility for instant image conversion to WebP format with a simple right-click.
MIT License
7 stars 0 forks source link

Great tool and implementation... request #1

Open jjchawaii opened 1 month ago

jjchawaii commented 1 month ago

Just curious if it's possible to reverse the conversion though. To still have a context menu option that can convert from Webp TO something like PNG or JPG. I am trying to add covert art to thousands of MP4s but the cover art is all in Webp format and my tagging software only recognizes jpg or png.

codeautopilot[bot] commented 1 month ago

Potential solution

To address the user's request for converting WebP files to PNG or JPG, we need to update the batch script, registry setup, and Python script to handle both conversions (to and from WebP). The solution involves:

  1. Modifying the batch script to detect the file type and call the appropriate Python script.
  2. Updating the registry setup to add context menu options for converting WebP files to PNG or JPG.
  3. Extending the Python script to handle conversions from WebP to PNG or JPG.

How to implement

Update WebP Converter.bat

Modify the batch script to detect the file type and call the appropriate Python script for conversion.

@echo off
setlocal enabledelayedexpansion

REM Loop through all selected files
for %%A in (%*) do (
   REM Get the full path of the input file
   set "input_file=%%~dpA%%~nxA"

   REM Get the directory of the input file
   set "input_dir=%%~dpA"

   REM Remove trailing backslash from input_dir
   if "!input_dir:~-1!"=="\" set "input_dir=!input_dir:~0,-1!"

   REM Get the file extension
   set "file_ext=%%~xA"

   REM Check if the file is a WebP file
   if /I "!file_ext!"==".webp" (
       REM Convert the WebP file to PNG or JPG in the same directory
       start /min python "C:\WebP Converter\convert_to_webp.py" "!input_file!" "!input_dir!" %2
   ) else (
       REM Convert the input file to WebP in the same directory
       start /min python "C:\WebP Converter\convert_to_webp.py" "!input_file!" "!input_dir!" webp
   )
)

Update setup.reg

Add new context menu entries for WebP files to convert them to PNG or JPG.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\SystemFileAssociations\.jpg\shell\WebPConverter]
@="Convert to WebP"
"Icon"="C:\\WebP Converter\\icon.ico"

[HKEY_CLASSES_ROOT\SystemFileAssociations\.jpg\shell\WebPConverter\command]
@="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.png\shell\WebPConverter]
@="Convert to WebP"
"Icon"="C:\\WebP Converter\\icon.ico"

[HKEY_CLASSES_ROOT\SystemFileAssociations\.png\shell\WebPConverter\command]
@="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.jpeg\shell\WebPConverter]
@="Convert to WebP"
"Icon"="C:\\WebP Converter\\icon.ico"

[HKEY_CLASSES_ROOT\SystemFileAssociations\.jpeg\shell\WebPConverter\command]
@="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.webp\shell\ConvertToPNG]
@="Convert to PNG"
"Icon"="C:\\WebP Converter\\icon.ico"

[HKEY_CLASSES_ROOT\SystemFileAssociations\.webp\shell\ConvertToPNG\command]
@="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\" png"

[HKEY_CLASSES_ROOT\SystemFileAssociations\.webp\shell\ConvertToJPG]
@="Convert to JPG"
"Icon"="C:\\WebP Converter\\icon.ico"

[HKEY_CLASSES_ROOT\SystemFileAssociations\.webp\shell\ConvertToJPG\command]
@="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\" jpg"

Update convert_to_webp.py

Extend the Python script to handle conversions from WebP to PNG or JPG.

from PIL import Image
import os
import sys

def convert_to_webp(input_files, output_folder):
    for input_path in input_files:
        try:
            with Image.open(input_path) as img:
                base_name = os.path.splitext(os.path.basename(input_path))[0]
                output_path = os.path.join(output_folder, f"{base_name}.webp")
                img.save(output_path, 'webp')
                print(f"Converted {input_path} to webp.")
        except Exception as e:
            print(f"Error converting {input_path}: {str(e)}")

def convert_from_webp(input_files, output_folder, output_format):
    for input_path in input_files:
        try:
            with Image.open(input_path) as img:
                base_name = os.path.splitext(os.path.basename(input_path))[0]
                output_path = os.path.join(output_folder, f"{base_name}.{output_format}")
                img.save(output_path, output_format)
                print(f"Converted {input_path} to {output_format}.")
        except Exception as e:
            print(f"Error converting {input_path}: {str(e)}")

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Usage: python convert_to_webp.py input_file_or_folder output_folder output_format")
        sys.exit(1)

    input_files = sys.argv[1:-2]
    output_folder = sys.argv[-2]
    output_format = sys.argv[-1].lower()

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    if output_format == 'webp':
        convert_to_webp(input_files, output_folder)
    elif output_format in ['png', 'jpg', 'jpeg']:
        convert_from_webp(input_files, output_folder, output_format)
    else:
        print(f"Unsupported output format: {output_format}")
        sys.exit(1)

This solution ensures that the batch file can handle both types of conversions based on the file type, and the Python script can convert WebP files to PNG or JPG as requested.

Click here to create a Pull Request with the proposed solution

Files used for this task:

Changes on WebP Converter.bat To address the user's request for converting WebP files to PNG or JPG, we need to modify the `WebP Converter.bat` file to include logic that detects WebP files and calls the appropriate Python script for conversion. Here's a step-by-step plan and the updated code: ### Plan 1. **Detect File Type**: Add logic to check if the input file is a WebP file. 2. **Call Appropriate Script**: Depending on the file type, call the appropriate Python script for conversion. 3. **Update Python Script Path**: Ensure the correct Python script is called for converting WebP to PNG or JPG. ### Updated `WebP Converter.bat` ```batch @echo off setlocal enabledelayedexpansion REM Loop through all selected files for %%A in (%*) do ( REM Get the full path of the input file set "input_file=%%~dpA%%~nxA" REM Get the directory of the input file set "input_dir=%%~dpA" REM Remove trailing backslash from input_dir if "!input_dir:~-1!"=="\" set "input_dir=!input_dir:~0,-1!" REM Get the file extension set "file_ext=%%~xA" REM Check if the file is a WebP file if /I "!file_ext!"==".webp" ( REM Convert the WebP file to PNG or JPG in the same directory start /min python "C:\WebP Converter\convert_from_webp.py" "!input_file!" "!input_dir!" ) else ( REM Convert the input file to WebP in the same directory start /min python "C:\WebP Converter\convert_to_webp.py" "!input_file!" "!input_dir!" ) ) ``` ### Explanation 1. **File Extension Detection**: The script now includes a check for the file extension using `%%~xA`. 2. **Conditional Logic**: If the file extension is `.webp`, it calls `convert_from_webp.py` to handle the conversion from WebP to PNG or JPG. Otherwise, it calls `convert_to_webp.py` to handle the conversion to WebP. This update ensures that the batch file can handle both types of conversions based on the file type, addressing the user's request effectively.
Changes on setup.reg To address the user's request for converting WebP files to PNG or JPG, we need to update the `setup.reg` file to include new context menu entries for WebP files. This will allow users to right-click on WebP files and convert them to either PNG or JPG. Here is the updated `setup.reg` file with the necessary registry entries: ### Updated `setup.reg` ```reg Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\SystemFileAssociations\.jpg\shell\WebPConverter] @="Convert to WebP" "Icon"="C:\\WebP Converter\\icon.ico" ; Replace with the path to your custom icon [HKEY_CLASSES_ROOT\SystemFileAssociations\.jpg\shell\WebPConverter\command] @="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\"" [HKEY_CLASSES_ROOT\SystemFileAssociations\.png\shell\WebPConverter] @="Convert to WebP" "Icon"="C:\\WebP Converter\\icon.ico" ; Replace with the path to your custom icon [HKEY_CLASSES_ROOT\SystemFileAssociations\.png\shell\WebPConverter\command] @="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\"" [HKEY_CLASSES_ROOT\SystemFileAssociations\.jpeg\shell\WebPConverter] @="Convert to WebP" "Icon"="C:\\WebP Converter\\icon.ico" ; Replace with the path to your custom icon [HKEY_CLASSES_ROOT\SystemFileAssociations\.jpeg\shell\WebPConverter\command] @="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\"" [HKEY_CLASSES_ROOT\SystemFileAssociations\.webp\shell\ConvertToPNG] @="Convert to PNG" "Icon"="C:\\WebP Converter\\icon.ico" ; Replace with the path to your custom icon [HKEY_CLASSES_ROOT\SystemFileAssociations\.webp\shell\ConvertToPNG\command] @="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\" png" [HKEY_CLASSES_ROOT\SystemFileAssociations\.webp\shell\ConvertToJPG] @="Convert to JPG" "Icon"="C:\\WebP Converter\\icon.ico" ; Replace with the path to your custom icon [HKEY_CLASSES_ROOT\SystemFileAssociations\.webp\shell\ConvertToJPG\command] @="\"C:\\WebP Converter\\WebP Converter.bat\" \"%1\" jpg" ``` ### Explanation: 1. **Existing Entries**: The existing entries for `.jpg`, `.png`, and `.jpeg` files remain unchanged. These entries allow converting these file types to WebP. 2. **New Entries for WebP**: - **Convert to PNG**: Adds a context menu entry for `.webp` files to convert them to PNG. - **Convert to JPG**: Adds a context menu entry for `.webp` files to convert them to JPG. Each new entry points to the `WebP Converter.bat` script with an additional argument (`png` or `jpg`) to specify the desired output format. ### Next Steps: 1. **Update `WebP Converter.bat`**: Modify the batch script to handle the new arguments and call the appropriate Python script for conversion. 2. **Update `convert_to_webp.py`**: Extend the Python script to include functionality for converting WebP files to PNG or JPG. By following these steps, you will enable the functionality to convert WebP files to PNG or JPG directly from the context menu.
Changes on convert_to_webp.py To extend the `convert_to_webp.py` script to include functionality for converting WebP files to PNG or JPG, we need to add a new function that handles the conversion from WebP to the desired formats. Here's a step-by-step plan to achieve this: 1. **Import Necessary Libraries**: Ensure that the required libraries are imported. 2. **Define a New Function**: Create a function to handle the conversion from WebP to PNG or JPG. 3. **Update the Main Logic**: Modify the main logic to call the appropriate function based on the input file type. Here's the updated script: ```python # Import the necessary libraries from PIL import Image # Pillow library for image processing import os # OS library for file and directory operations import sys # Sys library for system-related operations # Define a function to convert input image files to WebP format def convert_to_webp(input_files, output_folder): # Loop through each input file for input_path in input_files: try: # Open the input image using Pillow's Image.open method with Image.open(input_path) as img: # Get the base name of the input file without the extension base_name = os.path.splitext(os.path.basename(input_path))[0] # Construct the output file path with the .webp extension output_path = os.path.join(output_folder, f"{base_name}.webp") # Save the image in WebP format at the specified output path img.save(output_path, 'webp') # Print a message indicating successful conversion print(f"Converted {input_path} to webp.") except Exception as e: # Print an error message if an exception occurs during conversion print(f"Error converting {input_path}: {str(e)}") # Define a function to convert WebP files to PNG or JPG format def convert_from_webp(input_files, output_folder, output_format): # Loop through each input file for input_path in input_files: try: # Open the input WebP image using Pillow's Image.open method with Image.open(input_path) as img: # Get the base name of the input file without the extension base_name = os.path.splitext(os.path.basename(input_path))[0] # Construct the output file path with the specified extension output_path = os.path.join(output_folder, f"{base_name}.{output_format}") # Save the image in the specified format at the output path img.save(output_path, output_format) # Print a message indicating successful conversion print(f"Converted {input_path} to {output_format}.") except Exception as e: # Print an error message if an exception occurs during conversion print(f"Error converting {input_path}: {str(e)}") # Check if the script is being run as the main program if __name__ == "__main__": # Check if the correct number of command-line arguments is provided if len(sys.argv) < 4: print("Usage: python convert_to_webp.py input_file_or_folder output_folder output_format") sys.exit(1) # Extract the input files (all arguments except the last two) and the output folder (second last argument) input_files = sys.argv[1:-2] output_folder = sys.argv[-2] output_format = sys.argv[-1].lower() # Check if the specified output folder doesn't exist, and create it if necessary if not os.path.exists(output_folder): os.makedirs(output_folder) # Determine the conversion direction based on the output format if output_format == 'webp': convert_to_webp(input_files, output_folder) elif output_format in ['png', 'jpg', 'jpeg']: convert_from_webp(input_files, output_folder, output_format) else: print(f"Unsupported output format: {output_format}") sys.exit(1) ``` ### Explanation: 1. **New Function `convert_from_webp`**: This function handles the conversion from WebP to PNG or JPG. It takes the input files, output folder, and desired output format as arguments. 2. **Main Logic Update**: The script now checks the desired output format and calls the appropriate conversion function (`convert_to_webp` or `convert_from_webp`). This update allows the script to handle both conversions to WebP and from WebP to PNG or JPG, based on the user's needs.
Code-Parth commented 1 month ago

Just curious if it's possible to reverse the conversion though. To still have a context menu option that can convert from Webp TO something like PNG or JPG. I am trying to add covert art to thousands of MP4s but the cover art is all in Webp format and my tagging software only recognizes jpg or png.

Hey 👋🏻

You can try my upgraded project on this offc here https://github.com/Code-Parth/OFFC-Offline-File-Converter/tree/main/WINDOWS

And update the setup.reg to set your path manually.