Resize image with QPixmap

1

I'm trying to change the size of the image but it does not work, this is the code:

 pixi = QtGui.QPixmap.fromImage(image)
 pixi.scaledToWidth(150)
 pixi.scaledToHeight(150)
 self.label.resize(150,150)

 self.label.setPixmap(pixi)

but it simply stays with the same original dimensions.

    
asked by Revsky01 18.07.2018 в 08:01
source

1 answer

1

QPixmap.scaledToHeight and QPixmap.scaledToWidth do not perform the scaling " in-place ", return a new instance of QPixmap . You should therefore assign the output of the method to a new variable: scaled_pixi = pixi.scaledToWidth(150) .

On the other hand, if you use QPixmap.scaledToHeight the image is scaled to adjust the specified height, automatically adjusting the width  to maintain the aspect ratio of the image and therefore will be higher or lower than the height specified based on this relationship. The same thing happens with QPixmap.scaledToWidth , so it does not make sense for you to use both simultaneously.

pixi = QtGui.QPixmap.fromImage(image).scaledToWidth(150)
self.label.setPixmap(pixi)

If you need to scale the image to a height and width given without maintaining the aspect ratio use QPixmap.scaled :

pixi = QtGui.QPixmap.fromImage(image).scaled(150, 150)
self.label.setPixmap(pixi)

If you want the image to be scaled keeping the aspect ratio but to remain within a given height and width rectangle, you just have to use the parameter aspectRatioMode of QPixmap.scaled (default is Qt.IgnoreAspectRatio ):

pixi = QtGui.QPixmap.fromImage(image).scaled(150, 150, QtCore.Qt.KeepAspectRatio)

this makes for an original image of 300 x 200 to be scaled to 150 x 100, or one of 200 x 300 to scale to 100 x 150.

    
answered by 18.07.2018 / 09:37
source