I saw an other thread talking about this, but I'm not succeeding in the display of my image.
Currently, I'm downloading my image like this :
void MyClass::imgHandle() {
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
QUrl url(_code.c_str());
QNetworkReply* reply = nam->get(QNetworkRequest(url));
QEventLoop eventLoop;
connect(reply,SIGNAL(finished()),&eventLoop,SLOT(quit()));
eventLoop.exec();
if (reply->error() == QNetworkReply::NoError)
{
QImageReader imageReader(reply);
imageReader.setAutoDetectImageFormat (false);
_img = imageReader.read();
}
}
_code is built from a code got from a Json parsing, and the url looks like this : http://l.yimg.com/a/i/us/we/52/33.gif
_img is a QImage in my class.
And in my other class I do this :
int OtherClass::displayWeather()
{
MyClass mC = new MyClass;
mC->exec() // Where I get the code from the Json
QLabel *imgWeather = new QLabel(this);
imgWeather->setPixmap(QPixmap::fromImage(mC->getImg()));
// getImg() return a QImage.
//The QImage created in MyClass.
imgWeather->setGeometry(1700, 0, 120, 120);
}
And at the end .. Nothing is displayed !
You should check the QImageReader::read result:
QImageReader imageReader(reply);
imageReader.setAutoDetectImageFormat(false);
QImage _img = imageReader.read();
if (_img.isNull())
{
qDebug() << imageReader.errorString();
}
In your case the error is "Unsupported image format".
By default QImageReader tries to autodetect the image format and you've just disabled it by calling setAutoDetectImageFormat(false). Remove it and QImageReader will do the job.
Related
this is literally my first question in a forum.
So I'm a Qt newbie and I'm stuck at this little detail.
I'm creating this application that takes pictures and saves them, but the issue is that it saves then in a "JPEG" format and i need them in "PNG" or "GIF" or "tiff" and i I've tried a lot of stuff but nothing worked, so here's my code :
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
_camera_view = new QCameraViewfinder();
_take_image_button = new QPushButton("Take Image");
_turn_camera_off = new QPushButton("Turn Off");
_turn_camera_on= new QPushButton("Turn On");
_central_widget = new QWidget();
setCentralWidget(_central_widget);
_setup_ui();
_setup_camera_devices();
set_camera(QCameraInfo::defaultCamera());
connect(_take_image_button, &QPushButton::clicked, [this]{
_image_capture.data()->capture();});
connect(_turn_camera_off, &QPushButton::clicked, [this]{_camera.data()->stop();});
connect(_turn_camera_on, &QPushButton::clicked, [this]{_camera.data()->start();});}
You should get QImage in some point of your work. It has save member. Example from cited documentation:
QImage image;
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG"); // writes image into ba in PNG format
So the usage in context of QCameraImageCapture goes something like that:
QObject::connect(cap, &QCameraImageCapture::imageCaptured, [=] (int id, QImage img) {
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
img.save(&buffer, "PNG");
});
For anyone that might encounter this problem in the future, here's the solution i've found :
_image_capture->setCaptureDestination(QCameraImageCapture::CaptureToBuffer);
QObject::connect(_image_capture.data(), &QCameraImageCapture::imageCaptured, [=] (int id, QImage img) {
fileName = "image.png";
path = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation) + "/" + fileName;
img.save(path, "PNG");
});
I want to extract informations from youtube using Qt (QNetworkAccessManager). While the code below works with other websides, i dont get any data from youtube. Any idea what the configuration of QNetworkRequest should be?
PS. Yes i know i can achieve it by using YoutubeApi.
Youtube::Youtube(QObject *parent) : QObject(parent)
{
manager = new QNetworkAccessManager(this);
QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(readyRead(QNetworkReply*)));
}
void Youtube::makeRequest()
{
qDebug() << "YOUTUBE::makeRequest()";
request.setUrl(QUrl("www.youtube.com/"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
manager->get(request);
}
void Youtube::readyRead(QNetworkReply *replay)
{
qDebug() << replay->readAll();
QByteArray dataTemp = replay->readAll();
website = dataTemp.toStdString();
}
You can try this to get info about a video and store in a QJsonDocument object:
QNetworkAccessManager* net = new QNetworkAccessManager(this);
net->get(QNetworkRequest(QUrl("https://noembed.com/embed?
url=https://www.youtube.com/watch?v=dQw4w9WgXcQ")));
connect(net, &QNetworkAccessManager::finished,[](QNetworkReply* reply)
{
QString output = reply->readAll();
QJsonDocument doc;
QJsonParseError errorPtr;
doc = QJsonDocument::fromJson(output.toUtf8(), &errorPtr);
if(! doc.isNull())
{
QJsonObject videoInfoJson = doc.object();
qDebug() <<videoInfoJson.value("title").toString();
}
});
I expanded the Qt Imageviewer example by some functionality. I basically want to add a save function. In this example there are two functions of the same class handling the picture open process:
void ImageViewer::open()
{
QStringList mimeTypeFilters;
foreach (const QByteArray &mimeTypeName, QImageReader::supportedMimeTypes())
mimeTypeFilters.append(mimeTypeName);
mimeTypeFilters.sort();
const QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
QFileDialog dialog(this, tr("Open File"),
picturesLocations.isEmpty() ? QDir::currentPath() : picturesLocations.last());
dialog.setAcceptMode(QFileDialog::AcceptOpen);
dialog.setMimeTypeFilters(mimeTypeFilters);
dialog.selectMimeTypeFilter("image/jpeg");
while (dialog.exec() == QDialog::Accepted && !loadFile(dialog.selectedFiles().first())) {}
}
and
bool ImageViewer::loadFile(const QString &fileName)
{
QImageReader reader(fileName);
reader.setAutoTransform(true);
const QImage image = reader.read();
if (image.isNull()) {
QMessageBox::information(this, QGuiApplication::applicationDisplayName(),
tr("Cannot load %1.").arg(QDir::toNativeSeparators(fileName)));
setWindowFilePath(QString());
imageLabel->setPixmap(QPixmap());
imageLabel->adjustSize();
return false;
}
imageLabel->setPixmap(QPixmap::fromImage(image));
scaleFactor = 1.0;
printAct->setEnabled(true);
fitToWindowAct->setEnabled(true);
convAct->setEnabled(true); // so the image can be converted if it was loaded ...
updateActions();
if (!fitToWindowAct->isChecked()) {
imageLabel->adjustSize();
}
setWindowFilePath(fileName);
return true;
}
So I added a save button in the menus, and in the ImageViewer.h class:
class ImageViewer : public QMainWindow
{
Q_OBJECT
public:
ImageViewer();
bool loadFile(const QString &);
private slots:
void open();
void print();
void save(); // <---
Everything is fine, but I don't know how to get my Image in the new function, besides the fact, that I obviously make a wrong conversion from QPixmap to QImage - but I also tried replacing it with QPixmap test = imageLabel->pixmap() without any success.
void ImageViewer::save()
{
QImage test = imageLabel->pixmap();
qWarning()<< test;
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "BMP");
QString monobitmap = QString::fromLatin1(bytes.toBase64().data());
}
In the end, I want to save it as a monochrome bitmap (no matter what it was before). Sorry for posting a lot of code.
It sounds like your problem is that you have a QPixmap object and you need a QImage object. If that's the case, then you can convert a QPixmap into a QImage by calling the toImage() method on the QPixmap; it will return the resulting QImage object.
As for you converting the QImage to a monochrome bitmap, you should be able to do that by calling convertToFormat(QImage::Format_Mono) on your QImage. That call will return the new (1-bit) version of the QImage.
Generally, I've been searching for a while and could not find a serious answer. The problem is that I've a QString variable containing certain url, e.g. "C:/Users/Me/Desktop/image.png". How to open it and display the image in my application window?
I know the problem might seem trivial, however I can't find a working solution.
Load the image by using QPixmap and then show it with QLabel:
QString url = R"(C:/Users/Me/Desktop/image.png)";
QPixmap img(url);
QLabel *label = new QLabel(this);
label->setPixmap(img);
ImageViewer example
void LoadAvatar(const std::string &strAvatarUrl, QLabel &lable)
{
QUrl url(QString().fromStdString(strAvatarUrl));
QNetworkAccessManager manager;
QEventLoop loop;
QNetworkReply *reply = manager.get(QNetworkRequest(url));
QObject::connect(reply, &QNetworkReply::finished, &loop, [&reply, &lable,&loop](){
if (reply->error() == QNetworkReply::NoError)
{
QByteArray jpegData = reply->readAll();
QPixmap pixmap;
pixmap.loadFromData(jpegData);
if (!pixmap.isNull())
{
lable.clear();
lable.setPixmap(pixmap);
}
}
loop.quit();
});
loop.exec();
}
I am trying to display the image obtained from the get request made using networkaccess manager. I am able to compile and even able to run it. but I am unable to show the image in a Qlabel.
QNetworkAccessManager* nam;
void MainWindow::on_pushButton_clicked()
{
nam = new QNetworkAccessManager(this);
QUrl url("http://i.imgur.com/Uw7Fk.jpg");
QNetworkReply* reply = nam->get(QNetworkRequest(url));
if (reply->error() == QNetworkReply::NoError)
{
QImageReader imageReader(reply);
imageReader.setAutoDetectImageFormat (false);
QImage pic = imageReader.read();
ui->label_2->setPixmap(QPixmap::fromImage(pic));
}
}
Please tell me where I am going wrong.
The data in QNetworkReply is not ready immediately after the call to QNetworkAccessManager::get(). The call is asynchronous, and you need to connect to either the finished() signal of QNetworkAccessManager, or readyRead() signal of QNetworkReply before you attempt to retrieve any data.
To get image synchronously, you can use QEventLoop like below:
QNetworkAccessManager* nam;
void MainWindow::on_pushButton_clicked()
{
nam = new QNetworkAccessManager(this);
QUrl url("http://i.imgur.com/Uw7Fk.jpg");
QNetworkReply* reply = nam->get(QNetworkRequest(url));
QEventLoop eventloop;
connect(reply,SIGNAL(finished()),&eventloop,SLOT(quit()));
eventLoop.exec();
if (reply->error() == QNetworkReply::NoError)
{
QImageReader imageReader(reply);
imageReader.setAutoDetectImageFormat (false);
QImage pic = imageReader.read();
ui->label_2->setPixmap(QPixmap::fromImage(pic));
}
}