|
#!/usr/bin/env python |
|
import argparse |
|
from PIL import Image |
|
import os |
|
|
|
def remove_reddit_banner(image_path, dry_run=False): |
|
image = Image.open(image_path) |
|
try: |
|
has_banner = has_reddit_banner(image) |
|
except: |
|
has_banner = False |
|
image_mode = image.mode |
|
if not has_banner: |
|
return |
|
output_directory, filename = os.path.split(image_path) |
|
output_filename = os.path.splitext(filename)[0] + os.path.splitext(filename)[1] |
|
output_path = os.path.join(output_directory, output_filename) |
|
banner_height = get_banner_height(image) |
|
image_width, image_height = image.size |
|
if image.mode == 'RGBA': |
|
actual_format = 'PNG' |
|
output_path = os.path.splitext(output_path)[0] + f".{actual_format.lower()}" |
|
cropped_image = image.crop((0, 0, image_width, image_height - banner_height)) |
|
if dry_run: |
|
print(f'Would edit {image_path}') |
|
else: |
|
cropped_image.save(output_path, format=actual_format) |
|
if not dry_run: |
|
if os.path.exists(image_path) and os.path.splitext(image_path)[1].lower()[1:] != actual_format.lower(): |
|
os.remove(image_path) |
|
|
|
def get_banner_height(image): |
|
_, height = image.size |
|
banner_height = 0 |
|
while True: |
|
bottom_left_pixel = image.getpixel((0, height - banner_height - 1)) |
|
if bottom_left_pixel[:3] == (39, 39, 41): |
|
banner_height += 1 |
|
else: |
|
return banner_height |
|
|
|
def has_reddit_banner(image): |
|
width, height = image.size |
|
for x in range(width): |
|
for y in range(25): |
|
bottom_left_pixel = image.getpixel((x, height - y - 1)) |
|
if not bottom_left_pixel[:3] == (39, 39, 41): |
|
return False |
|
return True |
|
|
|
def process_directory(directory_path, dry_run=False): |
|
for filename in os.listdir(directory_path): |
|
if filename.lower().endswith(('.png', '.jpg', '.jpeg')): |
|
image_path = os.path.join(directory_path, filename) |
|
remove_reddit_banner(image_path, dry_run) |
|
|
|
if __name__ == "__main__": |
|
parser = argparse.ArgumentParser(description="Remove the reddit banner off images in a directory") |
|
parser.add_argument("directory_path", help="Path to the directory containing images") |
|
parser.add_argument("--dry-run", action='store_true', help="Dry runs") |
|
|
|
args = parser.parse_args() |
|
if os.path.exists(args.directory_path): |
|
process_directory(args.directory_path, args.dry_run) |
|
else: |
|
print(f"Error: The specified directory '{args.directory_path}' does not exist.") |
|
|