Created
September 18, 2020 17:43
-
-
Save kleysonr/c886411e994f63f0b4ae3ea480a75ebc to your computer and use it in GitHub Desktop.
Python - reference codes
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
---------------------------------------------------------------------------------------------- | |
# Listar todos todos arquivos de uma pasta | |
import glob | |
files = glob.glob('images/*') | |
---------------------------------------------------------------------------------------------- | |
# Listar todos arquivos de subpastas | |
import glob | |
files = glob.glob('images/**/*', recursive=True) | |
---------------------------------------------------------------------------------------------- | |
# Extrar o nome do arquivo do fullpath | |
import os | |
f = '/images/part1/image1.png' | |
filename = os.path.basename(f) | |
print(filename) # -> image1.png | |
---------------------------------------------------------------------------------------------- | |
# Extrar o path do fullpath | |
import os | |
f = '/images/part1/image1.png' | |
path = os.path.dirname(f) | |
print(path) # -> /images/part1 | |
---------------------------------------------------------------------------------------------- | |
# Separar nome do arquivo e extensao | |
import os | |
(file, ext) = os.path.splitext(filename) | |
---------------------------------------------------------------------------------------------- | |
# Converter uma imagem para base64 | |
import io | |
import base64 | |
def image_to_base64(image, type): | |
type = 'jpeg' if type == 'jpg' else type | |
with io.BytesIO() as buffer: | |
image.save(buffer, type) | |
return base64.b64encode(buffer.getvalue()).decode() | |
---------------------------------------------------------------------------------------------- | |
# Tornar uma imagem quadrada, preenchendo com `preto` o menor lado | |
from PIL import Image, ImageOps | |
def square_image(image): | |
(w, h) = image.size | |
if w > h: | |
border_size = (0, (w-h)//2) | |
image_size = (w, w) | |
elif h > w: | |
border_size = ((h-w)//2, 0) | |
image_size = (h, h) | |
else: | |
return image # Image already square | |
image = ImageOps.expand(image,border=border_size, fill='black') | |
image = image.resize(image_size) | |
return image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment