Created
September 22, 2020 23:41
-
-
Save xettri/cd7a66c1bb1351ee14830d5a6e7b33cb to your computer and use it in GitHub Desktop.
Resize and compress image using python
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
from __future__ import division | |
from PIL import Image, ImageOps | |
import os, sys | |
HEIGHT = 675 | |
WIDTH = 540 | |
QUALITY = 60 | |
OUTPUT_TYPE = "jpeg" | |
def getSize(i): | |
return i.size | |
def resize(i,w,h): | |
return i.resize((int(w),int(h)),Image.ANTIALIAS).convert('RGB') | |
def save(i,w,h): | |
n = str(w) + 'x' + str(h) + '~' + str(QUALITY) + '.' + OUTPUT_TYPE | |
i.save(n,optimize=True,quality=QUALITY) | |
def start(): | |
img = Image.open("./a.png") | |
[w, h] = getSize(img) | |
NEW_HEIGHT = HEIGHT | |
NEW_WIDTH = WIDTH | |
if h > w: | |
r = w / h | |
NEW_WIDTH = int( r * HEIGHT ) | |
elif w > h: | |
r = h / w | |
NEW_HEIGHT = int( r * WIDTH ) | |
img = resize(img,NEW_WIDTH,NEW_HEIGHT) | |
delta_w = WIDTH - NEW_WIDTH | |
delta_h = HEIGHT - NEW_HEIGHT | |
padding = (delta_w//2, delta_h//2, delta_w-(delta_w//2), delta_h-(delta_h//2)) | |
new_im = ImageOps.expand(img, padding, fill=(255,255,255)) | |
save(new_im,WIDTH,HEIGHT) | |
start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment