PIL: Miniatura y terminar con una imagen cuadrada
-
21-09-2019 - |
Pregunta
Llamando
image = Image.open(data)
image.thumbnail((36,36), Image.NEAREST)
mantendrá la relación de aspecto. Pero necesito terminar de mostrar la imagen como esta:
<img src="/media/image.png" style="height:36px; width:36px" />
¿Puedo tener un estilo de buzón, ya sea transparente o blanco alrededor de la imagen?
Solución
Pegue la imagen en una imagen transparente con el tamaño adecuado como fondo
from PIL import Image
size = (36, 36)
image = Image.open(data)
image.thumbnail(size, Image.ANTIALIAS)
background = Image.new('RGBA', size, (255, 255, 255, 0))
background.paste(
image, (int((size[0] - image.size[0]) / 2), int((size[1] - image.size[1]) / 2))
)
background.save("output.png")
EDIT: fija error de sintaxis
Otros consejos
PIL ya tiene una función para hacer exactamente eso:
from PIL import Image, ImageOps
thumb = ImageOps.fit(image, size, Image.ANTIALIAS)
from PIL import Image
import StringIO
def thumbnail_image():
image = Image.open("image.png")
image.thumbnail((300, 200))
thumb_buffer = StringIO.StringIO()
image.save(thumb_buffer, format=image.format)
fp = open("thumbnail.png", "w")
fp.write(thumb_buffer.getvalue())
fp.close()
O esto, tal vez ... (perdona espaguetis)
from PIL import Image
def process_image(image, size):
if image.size[0] > size[0] or image.size[1] > size[1]:
#preserve original
thumb = image.copy()
thumb.thumbnail(size,Image.ANTIALIAS)
img = thumb.copy()
img_padded = Image.new("RGBA",size)
img_padded.paste(image,(int((size[0]-image.size[0])/2),int((size[1]-image.size[1])/2)))
return img_padded
se puede envolver la respuesta de Nadia en esta función, lo que le da control sobre el tamaño y el fondo.
def make_square(im, min_size=36, fill_color=(255, 255, 255, 0)):
x, y = im.size
size = min(min_size, x, y)
new_im = Image.new('RGBA', (size, size), fill_color)
im.thumbnail((256, 256))
new_im.paste(im, (int((x - size) / 2), int((y -size) / 2))
return new_im
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow