import os def split_combined_image(combined_image_path, output_folder): # Read the combined image in binary mode with open(combined_image_path, 'rb') as combined_image_file: combined_data = combined_image_file.read() # Find the JPEG end marker (FFD9 in hex) in the combined image data jpeg_end_marker = b'\xFF\xD9' end_marker_index = combined_data.find(jpeg_end_marker) if end_marker_index == -1 or end_marker_index == len(combined_data) - 2: # No second image found if the end marker is not found or it is at the end of file print(f"Image '{combined_image_path}' cannot be split; no appended data found.") return False # Split the combined data at the end marker first_image_data = combined_data[:end_marker_index + 2] # Include the marker second_image_data = combined_data[end_marker_index + 2:] # Everything after the marker # Save the first part as the first image first_image_name = os.path.basename(combined_image_path).replace('.jpg', '_part1.jpg') output_first_image_path = os.path.join(output_folder, first_image_name) with open(output_first_image_path, 'wb') as first_image_file: first_image_file.write(first_image_data) print(f"First image data saved as '{output_first_image_path}'.") # Save the second part as the second image second_image_name = os.path.basename(combined_image_path).replace('.jpg', '_part2.jpg') output_second_image_path = os.path.join(output_folder, second_image_name) with open(output_second_image_path, 'wb') as second_image_file: second_image_file.write(second_image_data) print(f"Second image data saved as '{output_second_image_path}'.") return True def split_images_in_directory(input_folder, output_folder): # Ensure the output folder exists if not os.path.exists(output_folder): os.makedirs(output_folder) # Iterate over each image in the input folder for filename in os.listdir(input_folder): if filename.lower().endswith(('.jpg', '.jpeg', '.png')): image_path = os.path.join(input_folder, filename) print(f"Attempting to split '{image_path}'...") # Attempt to split the image if split_combined_image(image_path, output_folder): print(f"Successfully split '{image_path}'. Terminating script.") #return # Exit the function after a successful split # Usage split_images_in_directory('images', 'output_split_images')