Created
September 30, 2025 17:18
-
-
Save harrisonrw/0753e1850ced8532725d7c042261fef4 to your computer and use it in GitHub Desktop.
Encode a PNG file to base64 and write the encoded string to a file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """ | |
| Filename: base64_image_encoder.py | |
| Author: Robert Harrison | |
| Date: September 30, 2025 | |
| Description: Encode a PNG file to base64 and write the encoded string to a file. | |
| Usage: python base64_image_encoder.py <path_to_png_file> | |
| Example: pythonbase64_image_encoder.py input.py | |
| Base64 encoded image is saved to output.txt | |
| """ | |
| import base64 | |
| import sys | |
| def encode_image_to_base64(image_path): | |
| """Encode a PNG file to base64 and return the encoded string.""" | |
| try: | |
| with open(image_path, 'rb') as image_file: | |
| encoded_string = base64.b64encode(image_file.read()) | |
| return encoded_string.decode('utf-8') | |
| except FileNotFoundError: | |
| print(f"Error: File '{image_path}' not found.") | |
| return None | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| return None | |
| if __name__ == "__main__": | |
| if len(sys.argv) != 2: | |
| print("Usage: python base64_encoder.py <path_to_png_file>") | |
| sys.exit(1) | |
| image_path = sys.argv[1] | |
| encoded_image = encode_image_to_base64(image_path) | |
| if encoded_image: | |
| with open('output.txt', 'w') as output_file: | |
| output_file.write(encoded_image) | |
| print(f"Base64 encoded image saved to output.txt") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment