Created
April 26, 2017 13:11
-
-
Save tonybolanyo/6b8c048546c8a7c5b2263971e8e32124 to your computer and use it in GitHub Desktop.
Python: redimensionar imágenes rellenando con un color de fondo
This file contains 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
import logging | |
import os | |
from PIL import Image | |
logger = logging.getLogger(__name__) | |
logging.basicConfig(filename='resize.log', level=logging.DEBUG) | |
IMG_SIZE = (800, 800) | |
IMG_MODE = 'RGBA' | |
IMG_BACKGROUND = (255, 255, 255, 255) | |
def resize_image(src, output_dir): | |
filename = os.path.basename(src).lower() | |
dest_file = os.path.join(output_dir, filename) | |
logger.debug('Dir. Salida: %s' % output_dir) | |
logger.debug("Salida: %s" % dest_file) | |
print(os.path.join(output_dir, filename)) | |
original = Image.open(src) | |
original.thumbnail(IMG_SIZE, Image.ANTIALIAS) | |
img_width, img_height = original.size | |
width, height = IMG_SIZE | |
offset = ((width-img_width)//2, (height-img_height)//2) | |
image = Image.new(IMG_MODE, IMG_SIZE, IMG_BACKGROUND) | |
image.paste(original, offset) | |
image.save(dest_file, "JPEG") | |
if __name__ == "__main__": | |
folder = os.path.join(os.getcwd(), 'uploads') | |
output_dir = os.path.join(folder, "resized") | |
print('Directorio de salida: %s' % output_dir) | |
if not os.path.exists(output_dir): | |
logger.info('Creado directorio de salida') | |
os.mkdir(output_dir) | |
for entry in os.scandir(folder): | |
if entry.is_file(): | |
file_path = os.path.join(folder, entry.path) | |
logger.info('Imagen: %s' % file_path) | |
resize_image(file_path, output_dir) | |
print('Proceso terminado') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment