gpt4 book ai didi

python - QImage : URL instead of file path?

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:33 26 4
gpt4 key购买 nike

enter image description here

此代码将光栅像素图分配给标签。我可以简单地读取一个本地文件,而不是生成一个文件:

img = QtGui.QImage('/Users/user/Desktop/photo.jpg')

不知道有没有办法指定URL链接而不是文件路径?然后 QLabel 会直接从网络上获取它的像素图吗?

from PyQt4 import QtCore, QtGui


if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
if not QtGui.QApplication.instance():
app=QtGui.QApplication([])

window = QtGui.QWidget()
window.setLayout(QtGui.QVBoxLayout())

img = QtGui.QImage(32, 32, QtGui.QImage.Format_RGB32)
img.fill(QtCore.Qt.red)

pixmap = QtGui.QPixmap(img)
lbl = QtGui.QLabel()
lbl.setPixmap(pixmap)

icon = QtGui.QIcon(pixmap)
window.layout().addWidget(lbl)

window.show()
sys.exit(app.exec_())

最佳答案

据我所知,没有直接的方法让 QImage 或 QPixMap 直接从 URL 加载数据。但是您可以通过首先从 URL 中提取数据,然后将其加载到 QPixMap 来绕过它。

从 URL 获取数据:

import urllib2 
url_data = urllib2.urlopen(path).read()

现在将其加载到您的 QPixMap 中:

pixmap = QPixmap()
pixmap.loadFromData(url_data)
lbl.setPixmap(pixmap)

值得一提的是,您应该 try catch 异常,例如 urllib2.URLErrorInvalidURL,处理 URL protected (https) 等的情况。

关于python - QImage : URL instead of file path?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35284975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com