【问题标题】:Can't save PNG image into file无法将PNG图像保存到文件中
【发布时间】:2016-04-22 03:29:36
【问题描述】:

我在保存图像时遇到了一些问题。我必须通过 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;
}

【问题讨论】:

  • 有什么理由不使用较短的版本image.save(path)?此外,您没有检查 open() 的结果 - 这很糟糕。

标签: c++ image qt save png


【解决方案1】:

QImage 的 save 方法不以文件名作为参数,它任务一个 QFile。试试这个;

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

【讨论】:

【解决方案2】:

此任务不需要使用 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;
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多