pyqt5加载图片,等比例显示图片

原创:pyqt01/11/2023发布pv:0uv:0ip:0twitter #pyqt

原文地址:https://www.douyacun.com/article/2114b711521a0c8a935706d7a40e65c8

  1. 从本地加载图片
img = QImage("/Users/admin/Desktop/hello.png")
pimg = QPixmap.fromImage(image)
self.imgLabel.setPixmap(pimg)
  1. 图片铺满QLabel
img = QImage("/Users/admin/Desktop/hello.png")
pimg = QPixmap.fromImage(image)
self.imgLabel.setPixmap(pimg)
self.imgLabel.setScaledContents(True)
  1. 等比例显示未知大小的图片
img = QImage("/Users/admin/Desktop/hello.png")
pimg = QPixmap.fromImage(image)

fw = self.imgLabel.width() / width
fh = self.imgLabel.height() / height

factor = min(fw, fh)

width = int(width * factor)
height = int(height * factor)
nimg = img.scaled(width, height, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
self.imgLabel.setPixmap(nimg)