无法将PNG图像保存到文件中

Can't save PNG image into file

我在保存图像时遇到了一些问题。我必须按 rect 裁剪“1.png”并将其保存到文件,但出现了一个空文件(0 字节)。我做错了什么?

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的save方法没有文件名作为参数,它是一个QFile。试试这个;

    pixmap.save(&file, "PNG");

您不需要为此任务使用 QDataStream。直接使用QImagesave方法。你的代码应该是这样的:

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;
}

我认为您必须关闭之前打开的文件。此外,您根本不需要打开文件。你可以这样做:

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");