Search code examples
c++qtqimageqpixmapraw-data

Converting raw pixel data to QPixmap


I'm trying to convert raw pixel data to QPixmap but there is an error while converting qimage to qpixmap.

First, I send raw data from server A by qlocalsocket and Client B gets it.

This is Server A.

    if (clientSocket)
    {
        if (clientSocket->isOpen())
        {
            QByteArray block;
            QDataStream out(&block, QIODevice::WriteOnly);

            out.setVersion(QDataStream::Qt_5_7);
            const char* rc_data = reinterpret_cast<const char*>(r_data);
            out <<sizeof(strlen(rc_data))<< r_width << r_height << r_step;
            out.writeBytes(rc_data, strlen(rc_data));

            clientSocket->write(block);
            clientSocket->flush();
        }
    }

This is Client B.

    QByteArray block = connection->readAll();
    QDataStream in(&block, QIODevice::ReadOnly);
    in.setVersion(QDataStream::Qt_5_7); 
    char* data;
    size_t size;
    int width;
    int height;
    int step;
    while (!in.atEnd())
    {
        in >> size >> width >> height >> step;
        in.readBytes(data,size);
    }
    mutex.lock();
    receivePixmap = QPixmap::fromImage(QImage((unsigned char*)data, width, height, step, QImage::Format::Format_RGB888));
    mutex.unlock();
    ui.label->setPixmap(receivePixmap.scaled(ui.label->size(), Qt::KeepAspectRatio));
}

There is no error converting (unsigned char*)data to QImage but error while QPixmap::fromImage.

When I debug the code, sended and received data are same.

This is my error. Error : 0xC0000005: Access violation reading location 0xCDCDCDD1.

And occurs at here.

    #ifdef Q_COMPILER_RVALUE_REFS

    static QPixmap fromImage(QImage &&image, Qt::ImageConversionFlags flags = Qt::AutoColor)
        {
    return fromImageInPlace(image, flags);
    }
    #endif

Please share your idea thanks.


Solution

  • I Solved this problem

        writeBytes(rc_data,r_step*r_height)
        readBytes(data,r_step*r_height)
    

    I checked strlen(rc_data), but this size is not correct.

    Actual size of image was step*height.

    thank you guys~~~!!!