0

Rather than going to the filesystem to save and read back a PGM image file, I want to do this in memory. Can I somehow use a QBuffer as an in memory QFile to bypass saving to the filesystem:

            QFile filename(QString("/home/pi/frame-%1.pgm").arg(i));
            bool didOpen = filename.open(QIODevice::ReadWrite);
            qDebug() << "Did open file: " << didOpen << filename.fileName();
            int fileHandle = filename.handle();
            FILE * f = fdopen(dup(fileHandle), "wb");
            int res = fprintf(f, "P5 %d %d 65535\n", w, h);
            for (int y = 0; y < h; y++) {
                for (int x = 0; x < w; x++) {
                    uint16_t v = img[y*w+x];
                    //v = htobe16(v);
                    res = fwrite((uint8_t*)&v, sizeof(uint16_t), 1, f);
                }
            }
            fclose(f);

            QPixmap pixmap;
            bool didLoad = pixmap.load(QString("/home/pi/frame-%1.pgm").arg(i));
            emit updateScreen(pixmap);
4

1 回答 1

2

其实,是。

您已经准备好大部分数据。我们只需要把它变成QPixmap可以直接读取的格式。为此,我们使用QPixmap(const char *const[] xpm)构造函数从内存中制作像素图。巧合的是,此构造函数采用指针数组,而不是直接数组,这样就不必复制位图数据了!

未经测试的代码:

char *lines[] = (char **)malloc(sizeof(char *) * h + 1); // 1 extra for the header
char header[100]; 
sprintf(header, "P5 %d %d 65535\n", w, h);
lines[0] = header;
for (int y = 0; y < h; y++) {
   lines[y + 1] = (char *)&img[y * w]; // note y+1 offset
}

QPixmap pixmap(lines);
emit updateScreen(pixmap);
free(lines);

注意:sizeof(char *)返回 char指针h的大小,因此在第一行中,我们为标题分配行 + 1的指针数组。在将数组的第一“行”设置为标头后,我们将img内存块的地址偏移量复制到剩余的“行”中并将其提供给 QPixmap。之后我们就完成了。

于 2015-03-26T21:32:25.237 回答