app.py
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 |
from PIL import Image import base64 from io import BytesIO def image_to_base64(image_path): """Convert image to base64 string""" try: # Open the image with Image.open(image_path) as img: # Convert image to bytes using BytesIO buffer buffered = BytesIO() img.save(buffered, format=img.format) # Convert bytes to base64 string img_str = base64.b64encode(buffered.getvalue()) return img_str except Exception as e: print(f"Error converting image to base64: {e}") return None def base64_to_image(base64_string, output_path): """Convert base64 string back to image""" try: # Decode base64 string to bytes img_data = base64.b64decode(base64_string) # Create image from bytes img = Image.open(BytesIO(img_data)) # Save image img.save(output_path) return True except Exception as e: print(f"Error converting base64 to image: {e}") return False # Example usage if __name__ == "__main__": # Convert image to base64 input_path = "1.png" # Replace with your image path base64_str = image_to_base64(input_path) if base64_str: print("Image converted to base64 successfully!") print("Base64 string (first 100 chars):", base64_str[:100]) # Convert back to image output_path = "1.jpg" if base64_to_image(base64_str, output_path): print(f"Base64 converted back to image: {output_path}") |