J'ai besoin de redimensionner et de recadrer une image à une largeur et une hauteur spécifiques. J'ai été capable de construire une méthode qui créera une vignette carrée, mais je ne sais pas comment l'appliquer, quand la vignette souhaitée n'est pas carrée.Recadrage du moteur d'applications à une largeur et à une hauteur spécifiques
def rescale(data, width, height):
"""Rescale the given image, optionally cropping it to make sure the result image has the specified width and height."""
from google.appengine.api import images
new_width = width
new_height = height
img = images.Image(data)
org_width, org_height = img.width, img.height
# We must determine if the image is portrait or landscape
# Landscape
if org_width > org_height:
# With the Landscape image we want the crop to be centered. We must find the
# height to width ratio of the image and Convert the denominater to a float
# so that ratio will be a decemal point. The ratio is the percentage of the image
# that will remain.
ratio = org_height/float(org_width)
# To find the percentage of the image that will be removed we subtract the ratio
# from 1 By dividing this number by 2 we find the percentage that should be
# removed from each side this is also our left_x coordinate
left_x = (1- ratio)/2
# By subtract the left_x from 1 we find the right_x coordinate
right_x = 1 - left_x
# crop(image_data, left_x, top_y, right_x, bottom_y), output_encoding=images.PNG)
img.crop(left_x, 0.0, right_x, 1.0)
# resize(image_data, width=0, height=0, output_encoding=images.PNG)
img.resize(height=height)
# Portrait
elif org_width < org_height:
ratio = org_width/float(org_height)
# crop(image_data, left_x, top_y, right_x, bottom_y), output_encoding=images.PNG)
img.crop(0.0, 0.0, 1.0, ratio)
# resize(image_data, width=0, height=0, output_encoding=images.PNG)
img.resize(width=witdh)
thumbnail = img.execute_transforms()
return thumbnail
S'il y a une meilleure façon de le faire s'il vous plaît faites le moi savoir. Toute aide serait grandement appréciée.
Voici un diagramme expliquant le processus souhaité.
Merci,
Kyle
Merci. C'est exactement ce que je cherchais. –
merci beaucoup pour le code, fonctionne génial! – goggin13
thx! exactement ce que je cherchais – fceruti