Python:如何使用 PyQt 调整光栅图像的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21802868/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: How to Resize Raster Image with PyQt
提问by alphanumeric
I need to find a way to re-size an input raster image (such as jpg) to a specified width/height resolution (given in pixels). It would be great if PyQt while resizing a new image would keep an original image's aspect ratio (so there is no stretching but scaling only).
我需要找到一种方法将输入光栅图像(例如 jpg)重新调整为指定的宽度/高度分辨率(以像素为单位)。如果 PyQt 在调整新图像大小时能够保持原始图像的纵横比(因此没有拉伸而仅缩放),那就太好了。
src = '/Users/usrName/Images/originalImage.jpg' (2048x1024) (rectangular image 2:1 ratio) dest= '/Users/usrName/Images/originalImage_thumb.jpg' (64x64) (output image is square 1:1 ratio).
src = '/Users/usrName/Images/originalImage.jpg' (2048x1024) (矩形图像 2:1 比例) dest='/Users/usrName/Images/originalImage_thumb.jpg' (64x64) (输出图像为正方形 1:1比率)。
Thanks in advance!
提前致谢!
POSTED RESULTED FUNC:
发布结果功能:
...could be used to resize and to convert an image to any format QT supports so far... such as: 'bmp', 'gif', 'jpg', 'jpeg', 'png', 'pbm', 'tiff', 'svg', 'xbm'
...可用于调整图像大小并将图像转换为 QT 迄今为止支持的任何格式...例如:'bmp'、'gif'、'jpg'、'jpeg'、'png'、'pbm'、 'tiff'、'svg'、'xbm'
def resizeImageWithQT(src, dest):
    pixmap = QtGui.QPixmap(src)
    pixmap_resized = pixmap.scaled(720, 405, QtCore.Qt.KeepAspectRatio)
    if not os.path.exists(os.path.dirname(dest)): os.makedirs(os.path.dirname(dest))
    pixmap_resized.save(dest)
采纳答案by ekhumoro
Create a pixmap:
创建像素图:
    pixmap = QtGui.QPixmap(path)
and then use QPixmap.scaledToWidthor QPixmap.scaledToHeight:
然后使用QPixmap.scaledToWidth或QPixmap.scaledToHeight:
    pixmap2 = pixmap.scaledToWidth(64)
    pixmap3 = pixmap.scaledToHeight(64)
With a 2048x1024 image, the first method would result in an image that is 64x32, whilst the second would be 128x64. Obviously it is impossible to resize a 2048x1024 image to 64x64 whilst keeping the same aspect ratio (because the ratios are different).
对于 2048x1024 的图像,第一种方法会生成 64x32 的图像,而第二种方法是 128x64。显然,不可能将 2048x1024 图像的大小调整为 64x64,同时保持相同的纵横比(因为比例不同)。
To avoid choosing between width or height, you can use QPixmap.scaled:
为了避免在宽度或高度之间进行选择,您可以使用QPixmap.scaled:
    pixmap4 = pixmap.scaled(64, 64, QtCore.Qt.KeepAspectRatio)
which will automatically adjust to the largest size possible.
这将自动调整到可能的最大尺寸。
To resize the image to an exact size, do:
要将图像调整为精确大小,请执行以下操作:
    pixmap5 = pixmap.scaled(64, 64)
Of course, in this case, the resulting image won't keep the same aspect ratio, unless the original image was also 1:1.
当然,在这种情况下,生成的图像不会保持相同的纵横比,除非原始图像也是 1:1。

