简体   繁体   English

转换std :: vector <uint8_t> 到QImage

[英]Convert std::vector<uint8_t> to QImage

I am trying to create QImage from std::vector. 我试图从std :: vector创建QImage。 I tried; 我试过了;

void FaceCutThread::convertImage(std::vector<uint8_t> &buf)
{
    QImage img(&buf[0], 300, 300, QImage::Format_ARGB32);

    emit isFinisedFaceCut(img);
}

and

void FaceCutThread::convertImage(std::vector<uint8_t> &buf)
{
    QImage img(buf.data(), 300, 300, QImage::Format_ARGB32);

    emit isFinisedFaceCut(img);
}

both two type of convertion didn't give any error;however, when I tried to show it in QLabel like; 两种类型的转换都没有给出任何错误;但是,当我试图在QLabel显示它时;

void MainWindow::handleFaceResults(QImage& buf)
{
    QImage myImage(buf);
    ui->lblRawImage->setPixmap(QPixmap::fromImage(myImage));
}

my app always unexpectedly finishing. 我的应用总是意外地完成。 Could you please help how I can convert to QImage correctly? 你能帮忙我如何正确转换为QImage吗?

EDIT: 编辑:

I can write image into file without any problem like; 我可以毫无问题地将图像写入文件;

bool save_file (const string &path, const vector<uint8_t> &data)
{
    std::ofstream os;
    os.open(path.c_str(), std::ios::out | std::ios::binary);
    if (!os.is_open())
        return false;

    os.write((const char*)data.data(), data.size());
    return true;
}

I solved a similar problem with QImageReader and QBuffer 我用QImageReaderQBuffer解决了类似的问题

QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(buf.data()), buf.size());
QBuffer buffer(data);
QImageReader reader(&buffer);
QImage img = reader.read();

You need to make sure that the std::vector<uint8_t> &buf holds enough data for the picture. 您需要确保std::vector<uint8_t> &buf为图片保存足够的数据。 For QImage::Format_ARGB32 I would expect that 4 bytes are required per sample, so buf.size() must be at least 300*300*4. 对于QImage :: Format_ARGB32,我希望每个样本需要4个字节,因此buf.size()必须至少为300 * 300 * 4。

What to do it it's less? 该怎么办呢? Well, in that case probably the size of the image is not 300x300 and you need to figure out how to discover that. 那么,在这种情况下,图像的大小可能不是300x300,你需要弄清楚如何发现它。 Or you can fill in buf with '0' to get the required size just to check that in that case everything works (or, better, nothing bad happens) 或者你可以用'0'填写buf以获得所需的大小,以便检查在这种情况下一切正常(或者更好,没有什么不好的事情发生)

You can use this. 你可以用它。

QImage img;
img.loadFromData(buf.data(), buf.size());
img.scaled(QSize(300,300), Qt::KeepAspectRatio);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM