#-*- coding:utf-8 -*-
import sys
import requests
import urllib2
import base64
import io
from io import BytesIO
from PIL import Image
try:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
except:
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import (QWidget, QLabel, QVBoxLayout)

from PyQt5.QtGui import QPixmap



class graphicsView(QLabel):
def __init__(self,parent=None):
super(graphicsView,self).__init__(parent)
self._parent=parent


class MyLineEdit(QWidget):
def __init__( self, parent=None ):
super(MyLineEdit, self).__init__(parent)
self.initui()
def initui(self):
headers = {
"User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36",
'Referer':'https://www.tujigu.com/bigimg.html'}

url='https://lns.hywly.com/a/1/33144/11.jpg'

req = requests.get(url,headers)
html=req.content
html= self.image_to_byte_array(html)
with open("1.png", "wb") as f:
f.write(html)



photo = QPixmap(self)
photo.scaled(0.5, Qt.KeepAspectRatio)

photo.loadFromData(html)


label= graphicsView(self)


label.setPixmap(photo)

layout =QVBoxLayout()
layout.addWidget(label)
self.setLayout(layout)

self.resize(500,505)

self.show()
def image_to_byte_array(self,html):#将jpg字节转换为png字节
byte_stream = BytesIO(html) # 把请求到的数据转换为Bytes字节流
roiImg = Image.open(byte_stream) # Image打开Byte字节流数据
#roiImg.show() #显示图片
imgByteArr = io.BytesIO()
roiImg.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
return imgByteArr

if __name__ == '__main__':


app = QApplication(sys.argv)

ap=MyLineEdit()
ap.show()

sys.exit(app.exec_())

思路 :因为jpg图片大多情况无法在Qt正常显示,故将jpg字节流转为png字节流,之后即可正常显示。

PyQt4 解决jpg图片不能正常显示问题_linux


本地图片

img = cv2.imread(filepath)  # 读取图像
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换图像通道
#img = cv2.imdecode(np.fromfile(im_name,dtype=np.uint8),-1)#中文路径时,替换上一行
x = img.shape[1] # 获取图像大小
y = img.shape[0]
frame = QImage(img, x, y, QImage.Format_RGB888)
self.image=QPixmap(frame)

一般来说这样也可以正常显示,不过可能个别图片显示异常。

with open(filepath, 'rb') as f:
text = f.read()
frame = self.image_to_byte_array(text)
self.image=QPixmap()
self.image.loadFromData(frame)

同理也可以读取本地jpg图片字节流装换为png,之后进行操作。