Skip to content

Instantly share code, notes, and snippets.

@naveen521kk
Last active January 31, 2024 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveen521kk/22cd316550466a64939bce090115c72a to your computer and use it in GitHub Desktop.
Save naveen521kk/22cd316550466a64939bce090115c72a to your computer and use it in GitHub Desktop.
A program to make an image as a square maintaining aspect ratio and fill white spaces for extra space.
# A program to make an image as a square maintaining aspect ratio and fill white spaces for extra space.
# I used this for instagram posts
from PIL import Image
import os
from pillow_heif import register_heif_opener
register_heif_opener()
# find largest width and length
max_height = 0
max_width = 0
for file in os.listdir():
if file == __file__ or file.endswith('.py') or not os.path.isfile(file):
continue
image = Image.open(file)
width, height = image.size
if width > max_width:
max_width = width
if height > max_height:
max_height = height
print(max_width, max_height)
max_width = int((max_height / 9) * 16)
print(max_width, max_height)
for file in os.listdir():
if file == __file__ or file.endswith('.py') or not os.path.isfile(file):
continue
image = Image.open(file)
orig_width, orig_height = image.size
#width = int((height / 9) * 16)
width = height = max(orig_width, orig_height)
result = Image.new("RGB", (width, height), (255, 255, 255))
result.paste(image, ((width - orig_width)// 2, (height - orig_height)// 2))
result.save(f"out/{os.path.basename(file)}-edited.jpg")
# A program to make an image as a square maintaining aspect ratio and fill white spaces for extra space.
# I used this for instagram posts
from PIL import Image
# find largest width and length
max_height = 0
max_width = 0
for i in range(1, 5):
image = Image.open(f"{i}.jpg")
width, height = image.size
if width > max_width:
max_width = width
if height > max_height:
max_height = height
print(max_width, max_height)
max_width = int((max_height / 9) * 16)
print(max_width, max_height)
for i in range(1, 5):
image = Image.open(f"{i}.jpg")
orig_width, orig_height = image.size
#width = int((height / 9) * 16)
width = height = max(orig_width, orig_height)
result = Image.new("RGB", (width, height), (255, 255, 255))
result.paste(image, ((width - orig_width)// 2, (height - orig_height)// 2))
result.save(f'{i}-edited.jpg')
from PIL import Image
import os
from pillow_heif import register_heif_opener
register_heif_opener()
for file in os.listdir():
if file == __file__ or file.endswith(".py") or not os.path.isfile(file):
continue
image = Image.open(file)
image.save(f"jpgs/{os.path.basename(file)}.jpg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment