w3resource

Python Program: Read and modify image as bytes

Python Bytes and Byte Arrays Data Type: Exercise-4 with Solution

Write a Python program that reads an image file into a bytes object and saves a modified copy.

Sample Solution:

Code:

def read_image(file_path):
    with open(file_path, "rb") as file:
        image_bytes = file.read()
    return image_bytes

def save_modified_image(file_path, modified_bytes):
    with open(file_path, "wb") as file:
        file.write(modified_bytes)

def main():
    try:
        input_image_path = "flowchart_image.png"
        output_image_path = "output_image.png"
        
        # Read the image into bytes
        original_image_bytes = read_image(input_image_path)
        
        # Modify the bytes (e.g., adding watermark)
        modified_image_bytes = original_image_bytes + b"Watermark"
        
        # Save the modified image
        save_modified_image(output_image_path, modified_image_bytes)
        
        print("Image read and modified successfully.")
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    main()

Output:

Image read and modified successfully.

In the exercise above the "read_image()" function reads an image file into bytes using the "rb" (read binary) mode. The "save_modified_image()" function saves a modified bytes object into an image file using the "wb" (write binary) mode. The "main()" function demonstrates the usage of these functions by reading an input image, changing the bytes (in this case, adding a watermark), and saving the modified image.

Flowchart:

Flowchart: Python Program: Read and modify image as bytes.

Previous: Python program to convert list of integers to bytearray.
Next: Convert hexadecimal string to bytes.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.