1. 程式人生 > >C++ QT 載入網路圖片、本地圖片

C++ QT 載入網路圖片、本地圖片

原始碼下載:C++_QT 載入圖片

QTShowImage.cpp

#include "QtShowImage.h"
#include <QMovie>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QPixmap>
#include<QImage>

QtShowImage::QtShowImage(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	connect(ui.pushButton, SIGNAL(pressed()), this, SLOT(on_pushButton_clicked()));
	connect(ui.pushButton_2, SIGNAL(pressed()), this, SLOT(on_pushButton_2_clicked()));

}

void QtShowImage::on_pushButton_clicked()
{
	currentPicture = new QPixmap;
	//獲取網路圖片
	QNetworkAccessManager *manager;
	manager = new QNetworkAccessManager(this);

	connect(manager, SIGNAL(finished(QNetworkReply*)),
		this, SLOT(replyFinished(QNetworkReply*)));
	manager->get(QNetworkRequest(QUrl("http://www.eutrom.com/images/case_unit_1.png")));
}

void QtShowImage::on_pushButton_2_clicked()
{
	currentPicture = new QPixmap("./Images/head.png");
	QPixmap tianqi_pixmap = currentPicture->scaled(ui.labelImage->width(), ui.labelImage->height(), Qt::KeepAspectRatio);
	ui.labelImage->setPixmap(tianqi_pixmap);
}

void QtShowImage::replyFinished(QNetworkReply *reply)
{
	if (reply->error() == QNetworkReply::NoError)
	{
		//獲取位元組流構造 QPixmap 物件 
		currentPicture->loadFromData(reply->readAll());
		QDateTime now;
		QString filename = now.currentDateTime().toString("yyMMddhhmmss.jpg");
		currentPicture->save(filename);//儲存圖片
		currentFileName = filename;
		////可以在onpaint中 用QPixmap 顯示currentPicture,則這種方法則不需要儲存
		QPixmap tianqi_pixmap = currentPicture->scaled(ui.labelImage->width(), ui.labelImage->height(), Qt::KeepAspectRatio);
		//Qt::IgnoreAspectRatio, Qt::SmoothTransformation);//設定圖片大小和label的長寬一致
		ui.labelImage->setPixmap(tianqi_pixmap);
		//顯示圖片,  
		QMovie *move = new QMovie(currentFileName);
		//ui->lableImg->setMovie(move);
		move->start();
	}
}

QtShowImage.h

#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_QtShowImage.h"
#include <QMovie>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QPixmap>
class QtShowImage : public QMainWindow
{
	Q_OBJECT

public:
	QtShowImage(QWidget *parent = Q_NULLPTR);

private:
	Ui::QtShowImageClass ui;
	QPixmap *currentPicture;
	QString	currentFileName;

private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void replyFinished(QNetworkReply * reply);
};

效果圖