Why does PIL thumbnail not resizing correctly?

2024/9/20 20:51:48

I am trying to create and save a thumbnail image when saving the original user image in the userProfile model in my project, below is my code:

def save(self, *args, **kwargs):super(UserProfile, self).save(*args, **kwargs)THUMB_SIZE = 45, 45image = Image.open(join(MEDIA_ROOT, self.headshot.name))fn, ext = os.path.splitext(self.headshot.name)image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)        thumb_fn = fn + '-thumb' + exttf = NamedTemporaryFile()image.save(tf.name, 'JPEG')self.headshot_thumb.save(thumb_fn, File(open(tf.name)), save=False)tf.close()super(UserProfile, self).save(*args, **kwargs)

Every thing is working OK, just this one thing.

The problem is that the thumbnail function only sets the width to 45 and doesn't change the ratio aspect of the image so I am getting an image of 45*35 for the one that I am testing on (short image).

Can any one tell me what am I doing wrong? How to force the aspect ratio I want?

P.S.: I've tried all the methods for size: tupal: THUMB_SIZE = (45, 45) and entering the sizes directly to the thumbnail function also.

Another question: what is the deference between resize and thumbnail functions in PIL? When to use resize and when to use thumbnail?

Answer

The image.thumbnail() function will maintain the aspect ratio of the original image.

Use image.resize() instead.

UPDATE

image = image.resize(THUMB_SIZE, Image.ANTIALIAS)        
thumb_fn = fn + '-thumb' + ext
tf = NamedTemporaryFile()
image.save(tf.name, 'JPEG')
https://en.xdnf.cn/q/72308.html

Related Q&A

Put the legend of pandas bar plot with secondary y axis in front of bars

I have a pandas DataFrame with a secondary y axis and I need a bar plot with the legend in front of the bars. Currently, one set of bars is in front of the legend. If possible, I would also like to pla…

Printing floats with a specific number of zeros

I know how to control the number of decimals, but how do I control the number of zeros specifically?For example:104.06250000 -> 104.0625 119.00000 -> 119.0 72.000000 -> 72.0

How do I make a matplotlib scatter plot square?

In gnuplot I can do this to get a square plot:set size squareWhat is the equivalent in matplotlib? I have tried this:import matplotlib matplotlib.use(Agg) import matplotlib.pyplot as plt plt.rcParams[…

Efficiently determining if a business is open or not based on store hours

Given a time (eg. currently 4:24pm on Tuesday), Id like to be able to select all businesses that are currently open out of a set of businesses. I have the open and close times for every business for ev…

parsing .xsd in python

I need to parse a file .xsd in Python as i would parse an XML. I am using libxml2. I have to parse an xsd that look as follow: <xs:complexType name="ClassType"> <xs:sequence><x…

How to get the params from a saved XGBoost model

Im trying to train a XGBoost model using the params below: xgb_params = {objective: binary:logistic,eval_metric: auc,lambda: 0.8,alpha: 0.4,max_depth: 10,max_delta_step: 1,verbose: True }Since my input…

Reverse Label Encoding giving error

I label encoded my categorical data into numerical data using label encoderdata[Resi] = LabelEncoder().fit_transform(data[Resi])But I when I try to find how they are mapped internally usinglist(LabelEn…

how to check if a value exists in a dataframe

hi I am trying to get the column name of a dataframe which contains a specific word,eg: i have a dataframe,NA good employee Not available best employer not required well mana…

Do something every time a module is imported

Is there a way to do something (like print "funkymodule imported" for example) every time a module is imported from any other module? Not only the first time its imported to the runtime or r…

Unit Testing Interfaces in Python

I am currently learning python in preperation for a class over the summer and have gotten started by implementing different types of heaps and priority based data structures.I began to write a unit tes…