Python: How to Resize Raster Image with PyQt

两盒软妹~` 提交于 2020-07-15 04:28:29

问题


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).

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).

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'

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)

回答1:


Create a pixmap:

    pixmap = QtGui.QPixmap(path)

and then use QPixmap.scaledToWidth or 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).

To avoid choosing between width or height, you can use 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.



来源:https://stackoverflow.com/questions/21802868/python-how-to-resize-raster-image-with-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!