【问题标题】:resize image in python so it can be saved from being stretch在 python 中调整图像大小,以便可以避免被拉伸
【发布时间】:2021-05-18 14:02:33
【问题描述】:

你知道我可以用来创建 CSS 属性功能的任何人吗 -> “object-fit:scale-down”同时生成 pdf 如果图像以不同的纵横比出现,我尝试了只给一个固定位置或根据高度比宽度大 20% 传递高度/重量 css,然后将其移动到垂直矩形框,如果宽度大于高度,则 20% 移动到水平框,如果差异低于 20%,则将其移动到方形框,但没有作品和图像最终显示出拉伸。如果可能的话,任何逻辑或解决方法都会有所帮助我想使用 PIL 并实现这一点......

语言-python3
使用的库 - jinja、xhtml2pdf、PIL

稍后将转换为 pdf 的示例 jinja 代码

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

尝试了 Python 代码


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'

【问题讨论】:

  • 请用不止一行更详细地解释您想要的逻辑。您的评论与您的​​代码或上面的文字不符。举个例子也会很有帮助。
  • @chillking 例如...如果图像尺寸为 215X215,我会将其视为方形图像。如果 (500X215) 高度大于宽度,则我将其视为垂直矩形图像,如果 (215X500) 宽度大于高度,我将其视为矩形图像。它在某些情况下工作,但对于某些图像被拉伸。我希望它会有所帮助。
  • 好的,if 条件 if width &gt; height: ... else: ... 不适合这个?例如,如果高度应该比宽度至少大 20% 我会做if height &gt; 1.2*width: ...

标签: python python-3.x jinja2 python-imaging-library xhtml2pdf


【解决方案1】:
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

这样我们可以为我的图像提供最大边界,PIL 将负责调整大小并将适合该边界的图像的高度和宽度传递给我...问题解决了。

【讨论】:

    【解决方案2】:

    30% 不太符合您的逻辑,但类似这样的方法可行:

    from PIL import Image
    
    image = Image.open('./image.png')
    
    width, height = image.size
    
    if width * 1.3 > height:
        new_height = width
        new_width = width
    else:
        new_height = height
        new_width = height
    
    image.resize([new_width, new_height]).save('./new_image.png')
    

    【讨论】:

    • 请检查我的逻辑是否添加了问题
    猜你喜欢
    • 2010-09-19
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多