|
| 1 | +from PIL import Image |
| 2 | +import os |
| 3 | + |
| 4 | +def convert_image(input_path, output_path, output_format): |
| 5 | + try: |
| 6 | + # Open the image |
| 7 | + with Image.open(input_path) as img: |
| 8 | + # Convert and save the image to the desired format |
| 9 | + img.save(output_path, format=output_format) |
| 10 | + print(f"Image converted successfully to {output_format} format.") |
| 11 | + except Exception as e: |
| 12 | + print(f"An error occurred: {e}") |
| 13 | + |
| 14 | +def main(): |
| 15 | + input_path = input("Enter the path to the input image: ") |
| 16 | + output_format = input("Enter the desired output format (e.g., JPEG, PNG, BMP, GIF): ").upper() |
| 17 | + |
| 18 | + # Validate output format |
| 19 | + if output_format not in ['JPEG', 'PNG', 'BMP', 'GIF']: |
| 20 | + print("Invalid output format. Please choose from JPEG, PNG, BMP, or GIF.") |
| 21 | + return |
| 22 | + |
| 23 | + # Extract the file name and extension |
| 24 | + file_name, file_extension = os.path.splitext(input_path) |
| 25 | + |
| 26 | + # If the input file already has an extension, remove it |
| 27 | + file_name_without_ext = file_name.split('.')[0] |
| 28 | + |
| 29 | + # Set the output path |
| 30 | + output_path = f"{file_name_without_ext}_converted.{output_format.lower()}" |
| 31 | + |
| 32 | + # Convert the image |
| 33 | + convert_image(input_path, output_path, output_format) |
| 34 | + |
| 35 | +if __name__ == "__main__": |
| 36 | + main() |
0 commit comments