【问题标题】:Reducing size of an image in PySide在 PySide 中减小图像的大小
【发布时间】:2013-08-15 11:09:05
【问题描述】:

我的要求是缩小图像的大小并显示在方形框(50 x 50)中。如果图像的大小小于方形框的大小,则图像应按原样显示。作为最初的尝试,我尝试使用以下代码,目的是减少所有图像的大小:

picSize = QtCore.QSize(lbl.width() / 2 , lbl.height() / 2)

但以下代码即使在使用后也不会减小图像的大小:

picSize = QtCore.QSize(lbl.width() / 4 , lbl.height() / 4)

请帮帮我。

import os
import sys

from PySide import QtGui, QtCore

class SecondExample(QtGui.QWidget):

    def __init__(self):
        super(SecondExample, self).__init__()
        self.initUI()

    def initUI(self):
        self.imgFolder = os.getcwd()


        self.widgetLayout = QtGui.QVBoxLayout(self)
        self.scrollarea = QtGui.QScrollArea()
        self.scrollarea.setWidgetResizable(True)
        self.widgetLayout.addWidget(self.scrollarea)
        self.widget = QtGui.QWidget()
        self.layout = QtGui.QVBoxLayout(self.widget)    
        self.scrollarea.setWidget(self.widget)

        self.layout.setAlignment(QtCore.Qt.AlignHCenter)

        for img in os.listdir(self.imgFolder):
            imgPath = os.path.join(self.imgFolder, img)
            actualImage = QtGui.QImage(imgPath)
            pixmap = QtGui.QPixmap(imgPath)

            lbl = QtGui.QLabel(self)
            lbl.setPixmap(pixmap)

            lbl.setScaledContents(True)

            picSize = QtCore.QSize(lbl.width() / 2 , lbl.height() / 2)
            lbl.resize(picSize)

            self.layout.addWidget(lbl)

        self.setGeometry(100, 100, 900, 700)
        self.setWindowTitle('Viewer')
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = SecondExample()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python qt python-2.7 pyside


    【解决方案1】:

    以下代码将满足您的要求:

                imgPath = os.path.join(self.imgFolder, img)
                actualImage = QtGui.QImage(imgPath)
                pixmap = QtGui.QPixmap(imgPath)
                pixmap = pixmap.scaled(500, 500, QtCore.Qt.KeepAspectRatio) 
                lbl = QtGui.QLabel(self)
                lbl.setPixmap(pixmap)
    
                lbl.setScaledContents(True)
    

    【讨论】:

    • “actualImage = QtGui.QImage(imgPath)”有什么作用?
    【解决方案2】:

    您可以使用scaledToWidth 或 scaledToHeightmethod on theQImage` 类。

    img= QtGui.QImage(imgPath)
    pixmap = QtGui.QPixmap(img.scaledToWidth(50))
    lbl = QtGui.QLabel(self)
    lbl.setPixmap(pixmap)
    

    【讨论】:

      【解决方案3】:

      您必须使用QPixmap::scaled 来扩展QPixmap

      pixmap.scaled(picSize)

      您可能想查看AspectRatio

      【讨论】:

        猜你喜欢
        • 2016-05-12
        • 1970-01-01
        • 2017-02-06
        • 2019-04-13
        • 1970-01-01
        • 1970-01-01
        • 2019-07-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多