Python:如何使用PyQt调整光栅图像的大小 [英] Python: How to Resize Raster Image with PyQt

查看:232
本文介绍了Python:如何使用PyQt调整光栅图像的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一种方法来将输入栅格图像(例如jpg)的大小调整为指定的宽度/高度分辨率(以像素为单位).如果PyQt在调整新图像的大小时将保持原始图像的宽高比(这样就不会拉伸,而只能缩放),那就太好了.

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)(矩形图像2:1比例) dest ='/Users/usrName/Images/originalImage_thumb.jpg'(64x64)(输出图像为1:1正方形比例).

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

提前谢谢!

......可用于调整大小并将图像转换为QT到目前为止支持的任何格式...例如:'bmp','gif','jpg','jpeg','png',' pbm","tiff","svg","xbm"

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

推荐答案

创建像素图:

    pixmap = QtGui.QPixmap(path)

,然后使用 QPixmap.scaledToWidth QPixmap.scaledToHeight :

    pixmap2 = pixmap.scaledToWidth(64)
    pixmap3 = pixmap.scaledToHeight(64)

对于2048x1024的图片,第一种方法生成的图片为64x32,而第二种方法生成的图片为128x64.显然,将2048x1024图像的尺寸调整为64x64是不可能的,同时要保持相同的宽高比(因为宽高比不同).

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

为避免在宽度或高度之间进行选择,您可以使用 QPixmap.scaled :

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)

当然,在这种情况下,除非原始图像也是1:1,否则所得图像将不会保持相同的宽高比.

Of course, in this case, the resulting image won't keep the same aspect ratio, unless the original image was also 1:1.

这篇关于Python:如何使用PyQt调整光栅图像的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆