Search code examples
pythonpython-3.xjinja2python-imaging-libraryxhtml2pdf

resize image in python so it can be saved from being stretch


do anyone you know anything I can use to create functionality of CSS property -> " object-fit:scale-down " while generating pdf if images are coming in a different aspect ratio i tried it with giving only one place fixed or passing the height/ weight css based on height 20% greater then width then moving it to vertically rectangle box if the width is greater then height 20% moving to horizontal box if it's under 20% difference moving it to a square box but none of that works and images end up showing stretch. any logic or workaround will be helpful if possible i want to use PIL and achieve this...

Language- python3
library used- jinja,xhtml2pdf, PIL

sample jinja code that is getting converted into pdf later

<img src="{{path}}" style="height:{{height}};width:{{width}};"  />

Python code tried


try:
                #logo fixes for diffrent size of logo
                im = Image.open('something')
                width,height = im.size
                #logic if logo is higher then 20% of width then it's vertically image if width is more then 20% of height then it's comes under horizontal catogory (20*width)/100  default is 2cm to 2cm for square image
                if height+(20*width)/100>width and height!=width: #horizontal 
                    data['width']='2cm' 
                    data['height']='4cm' 
                elif width+(20*height)/100>height and height!=width: #vertical
                    data['width']='4cm' 
                    data['height']='2cm' 
                else: #default
                    data['width']='2cm' 
                    data['height']='2cm' 
except Exception as imageerror:
    data['width']='2cm' 
    data['height']='2cm'


Solution

  • try:
      image = Image.open('something')
      image.thumbnail((700,700), Image.ANTIALIAS)
      image.save('something','JPEG',quality=100) #replace existing file
      height,width = image.size
    except exception as e:
      #Size extraction failed Print e 
      pass
    

    this way we can provide maximum boundaries for my images and PIL will take care of resizing and pass me the height and width of the image that fits in that boundaries ...Problem solved.