使用PIL调整图像大小以保持原始宽高比?



程序按预期运行,但它总是垂直扩展和水平压缩。我附加了调整图像大小的方法和main函数。不知道是什么问题!

from PIL import Image
def resize(image, new_width=100):
width, height = image.size                           
ratio = width / height / 1.65                        
new_height = int(ratio * new_width)                  
resized_img = image.resize((new_width, new_height))  
return resized_img                                   

def main(new_width=100):
path = input("Enter a valid pathname to an image: ")           
try:
image = PIL.Image.open(path)
except:
print(path, "is not a valid pathname to an image.")
return
new_img_data = convert_chars(grayscale(resize(image)))
pixel_count = len(new_img_data)
ascii_img = "n".join(new_img_data[i:(i + new_width)] for i in range(0, pixel_count, new_width))
print(ascii_img)
with open("ascii_image.txt", "w") as f:                    
f.write(ascii_img)
main()

这没有意义:

ratio = width / height ...                        
new_height = int(ratio * new_width)                  

假设宽度是100,然后除以单位。那么new_height应该恢复原始高度,对吧?而是宽度的平方除以高度。这是颠倒的。


请把东西修好然后给我们看改进后的代码。

最新更新