Can't save PNG image into file - c++

I have some troubles with image saving. I have to crop "1.png" by rect and save it to file, but an empty one is appearing (0 bytes). What am I doing wrong?
void RedactorForm::cropButtonSlot(int x1, int y1, int x2, int y2) {
QImage pixmap("1.png");
QRect rect(x1,y1,x2,y2);
pixmap=pixmap.copy(rect);
QString fileName("D:/yourFile.png");
QFile file(fileName);
file.open(QIODevice::WriteOnly);
QDataStream out(&file);
pixmap.save(fileName,0,100);
out <<pixmap;
}

QImage's save method does not take a file name as a parameter, it taske a QFile. Try this;
pixmap.save(&file, "PNG");

You don't need use QDataStream for this task. Use directly save method of QImage. Your code should be like this:
QImage pixmap("1.png");
...................
QString fileName("D:/yourFile.png");
QFile file(fileName);
if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
pixmap.save(&file, "PNG");
}
else {
qDebug() << "Can't open file: " << fileName;
}

I think you have to close the file which you opened before. Also you don't need to open the file at all. You can do that:
QRect rect(x1,y1,x2,y2);
QImage pixmap(x2-x1,y2-y1,QImage::Format_ARGB32);
pixmap.copy(rect);
QFile file("D:/yourFile.png");
pixmap.save(file.fileName(),"PNG");

Related

QT failed to load Image from Buffer

My work Environment : Qt 5.8 MSVC2015 64bit, QT GraphicsView, Windows 7 64 bit
I am loading image from buffer (a demon process is going send a image buffer), but it failed to create image with buffer.
QFile file("D:\\2.png");
if (!file.open(QFile::ReadOnly))
qDebug() << "Error failed to Open file";
QByteArray array = file.readAll();
array = array.toBase64();
QImage tempimage((uchar *)array.data(), 250, 250, QImage::Format_RGBX8888);
if (!tempimage.isNull()) {
///I always get this error
qDebug() << "Error!!! failed to create a image!";
}
Any idea what I am missing here ?
Why are you converting to base64?
Wait, where are you converting from PNG to an image plane?
Try bool QImage::loadFromData(const QByteArray &data, const char *format = Q_NULLPTR) to load the PNG instead of the CTor with the raw data.
If your wire format isn't PNG (and is in fact base64 encoded raw pixel data) then you want to convert FROM base64.
Thanks for all suggestion & help.
I fix my mistakes removed base64 conversion & loaded buffer using loadFromData with QByteArray reinterpret_cast:
Here is a final solution :
QFile file("D:\\2.png");
if (!file.open(QFile::ReadOnly))
qDebug() << "Error failed to Open file";
QByteArray array = file.readAll();
QImage tempimage;
//// This very important to cast in below format, QByteArray don't work as arguments.
tempimage.loadFromData(reinterpret_cast<const uchar *>(array.data()),array.size());
if (tempimage.isNull()) {
qDebug() << "Error!!! failed to create a image!";
}

Qt5: How to read/write the file in local file system

I'm new to Qt.In my app,I want to press a button and it will come out a QFileDialog to let me select the file in file system .So how to do that?
After that , here is my problem, I don't know which API in Qt works just like "open" in POSIX ? I think if I can open the file in the right way , this API will return me a file descriptor and I can read/write this file like open did in posix.
I read some documents and found some classes such as QFile QDataStream but I don't know if they are exactly what I want.
Those are exactly what you are looking for.
In particular, you can use some of the static methods of QFileDialog to get a reference to the file you want to open, like:
static QString getOpenFileName(QWidget * parent = 0, const QString & caption = QString(), const QString & dir = QString(), const QString & filter = QString(), QString * selectedFilter = 0, Options options = 0)
and then use a QFile and QDataStream or QTextStream to read the contents.
You'd use QDataStream for reading binary data most of the times, like follows:
QFile f(fileName);
if (f.open(QIODevice::ReadOnly)) {
QDataStream stream(&f);
int data;
stream >> data;
}
Otherwise you can read plain text with QTextStream as follows:
QTextStream stream(&f);
QString line;
do {
line = stream.readLine();
/* do something with the line */
} while (!line.isNull());
Qt docs are pretty complete, you just have to take your time and read them. There's also plenty of examples.
Only Reading:
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open file"), "", tr("all Files ()"));
QFile file(fileName);
if(file.open(QIODevice::ReadOnly)){
QByteArray arr = file.readAll();
file.close();
}
Only Writing:
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open file"), "", tr("all Files ()"));
QFile file(fileName);
if(file.open(QIODevice::WriteOnly)){
file.write(QBtyeArray("Heelo World"));
file.close();
}
Read and Write:
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open file"), "", tr("all Files ()"));
QFile file(fileName);
if(file.open(QIODevice::ReadWrite)){
QByteArray arr = file.readAll();
arr += " From Earth";
file.write(arr);
file.close();
}
if you use QDatastream you do not need resolve how many part you have written before,follow Below Code and I always use this method;
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
QDatastream out(&buffer);
out << QString("Hello World QString");
out << QByteArray("Hello World QByteArray");
out << int(55);
buffer.close();
QFile file(fileName);
if(file.open(QIIDevice::WriteOnly)){
file.write(buffer.data());
file.close();
}
and reading this file
QFile file(fileName);
if(file.open(QIIDevice::WriteOnly)){
QDatastream in(&file);
QString str;
QByteArray arr;
int integer;
in >> str;
in >> arr;
in >> integer;
file.close();
}
str is "Hello World QString";
arr is "Hello World QByteArray";
integer is 55;
QDataStream is adding extra bytes to file for your parts and if you read it with QDataStream, QDataStream solve how many parts and each part bytes instead of you.

QDataStream unable to serialize data

I am trying to follow the tutorial here and serialize Qt objects. Here is my code:
QFile file("/Users/kaustav/Desktop/boo.dat");
if (!file.open(QIODevice::WriteOnly)) {
qDebug() << "Cannot open file for writing: "
<< qPrintable(file.errorString()) << endl; //no error message gets printed
return 0;
}
QDataStream out(&file); // we will serialize the data into the file
out.setVersion(QDataStream::Qt_5_3); //adding this makes no difference
out << QString("the answer is"); // serialize a string
out << (qint32)42;
When I run this program, the file gets created in my desktop all right, but its size is 0 kB, it is blank. Naturally, when I then try this:
QFile file("/Users/kaustav/Desktop/boo.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file); // read the data serialized from the file
in.setVersion(QDataStream::Qt_5_3);
QString str;
qint32 w;
in >> str >> w;
I get a blank string in str. What am I doing wrong? If of any help, I am using Qt Creator 3.1.1 based on Qt 5.2.1.
Check if there are any errors returned when calling open and ensure you close the file with file.close() when you're finished with it.
As you're using Qt 5, you should really use QSaveFile instead, when saving the data.

Qt Creator combobox

How to write Combobox current text in a preexisting text file in hard drive? Here is my code:
void second::on_pushButton_4_clicked()
{
QFile file("vik.txt");
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QTextStream out(&file);
out << ui->comboBox_5->currentText() << "\n";
}
Maybe you forgot to close the file
void second::on_pushButton_4_clicked()
{
// Get comboBox text value
QString txt = ui->comboBox_5->currentText();
// Open file for writing
QFile file("vik.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
// Write in file
out << txt << "\n";
// Close file
file.close();
}
You have several issues in your code, let me enumerate them one-by-one:
You need this flag for "overwrite" as per your comment:
QIODevice::Truncate 0x0008 If possible, the device is truncated before it is opened. All earlier contents of the device are lost.
More importantly, have you checked whether the method returns after open with some error? If it does, please print out file.errorString() there:
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << file.errorString();
return;
}
On the most important note, you are likely facing the issue that the file is not in your current working directory. If the file resides beside the application executable, please change the corresponding line into your code to this:
QFile file(QCoreApplication::applicationDirPath() + "/vik.txt");

Opening a file from a Qt String

I am making a Qt application and I have a button to open a file, which is connected to a custom slot. This is the slot code so far:
void MainWindow::file_dialog() {
const QFileDialog *fd;
const QString filename = fd->getOpenFileName();
}
How could I have it then convert the file name to a const char *, open the file, read it and store the text in a QString, and then close the file. I am using Qt4.
To read the contents of a file, you can do this:
QString filename = QFileDialog::getOpenFileName();
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QString content = file.readAll();
file.close();