美文网首页
PyQt5中使用QLabel显示图片

PyQt5中使用QLabel显示图片

作者: 流浪的企鹅 | 来源:发表于2020-04-03 00:14 被阅读0次

QLabel显示图片需要首先使用QPixmap加载图片,然后在aLabel.setPixmap(aPixmap).

1. 从文件加载图片

  • 从文件创建QPixmap对象
  • 设置QLabel的位置和大小
  • 调用QLabel的setPixmap方法设置pix
        pix = QPixmap('sexy.jpg')

        lb1 = QLabel(self)
        lb1.setGeometry(0,0,500,210)
        lb1.setPixmap(pix)

2. 从文件加载图片,图片自适应大小

  • 从文件创建QPixmap对象
  • 设置QLabel的位置和大小
  • 调用QLabel的setPixmap方法设置pix
  • 设置QLabel中的图片自适应QLabel的大小
        pix = QPixmap('sexy.jpg')
        
        lb2 = QLabel(self)
        lb2.setGeometry(0,250,500,210)
        lb2.setPixmap(pix)
        lb2.setScaledContents(True)   #自适应QLabel大小

3. 从内存中加载图片

  • base64编码数组首先解码为字节码
  • 使用io.BytesIO(img_b64decode) 封装成流格式
  • 使用PIL的Image加载图片
  • 使用Image的toqpixmap() 函数转换为QPixmap
  • 使用QLabel的setPixmap方法,将pix赋值给QLabel进行绘制
from PIL import Image
import io
import base64

def set_img_on_label(lb, img_b64):
    img_b64decode = base64.b64decode(img_b64)  #[21:]
    img_io = io.BytesIO(img_b64decode)
    img=Image.open(img_io)
    pix = img.toqpixmap()
    lb.setScaledContents(True)  # 自适应QLabel大小
    lb.setPixmap(pix)

4. 测试代码

#!/usr/bin/env python 
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QLabel, QWidget, QApplication

import base64
import io
from PIL import Image

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        pix = QPixmap('sexy.jpg')

        lb1 = QLabel(self)
        lb1.setGeometry(0,0,500,210)
        lb1.setStyleSheet("border: 2px solid red")
        lb1.setPixmap(pix)

        lb2 = QLabel(self)
        lb2.setGeometry(0,250,500,210)
        lb2.setPixmap(pix)
        lb2.setStyleSheet("border: 2px solid red")
        lb2.setScaledContents(True)   #自适应QLabel大小

        self.lb3 = QLabel(self)
        self.lb3.setGeometry(0, 500, 500, 210)
        self.lb3.setPixmap(pix)
        self.lb3.setStyleSheet("border: 2px solid red")
        self.lb3.setScaledContents(True)  # 自适应QLabel大小

def set_img_on_label(lb, img_b64):
    img_b64decode = base64.b64decode(img_b64)  #[21:]
    img_io = io.BytesIO(img_b64decode)
    img=Image.open(img_io)
    pix = img.toqpixmap()
    lb.setScaledContents(True)  # 自适应QLabel大小
    lb.setPixmap(pix)

if __name__== '__main__':
    app = QApplication([]);  # argv)
    # icon = QIcon("logo.ico")
    # app.setWindowIcon(icon)
    win = Demo()
    win.show()
    sFile = open("sexy.jpg", "rb").read()
    img_b64 = base64.b64encode(sFile)
    set_img_on_label(win.lb3,img_b64)
    sys.exit(app.exec_())


相关文章

网友评论

      本文标题:PyQt5中使用QLabel显示图片

      本文链接:https://www.haomeiwen.com/subject/hvbqphtx.html