代码之家  ›  专栏  ›  技术社区  ›  PhilBot

带fwrite的内存QFile

  •  0
  • PhilBot  · 技术社区  · 10 年前

    我不想去文件系统保存和读回PGM映像文件,而是想在内存中这样做。我是否可以使用QBuffer作为内存中的QFile来绕过保存到文件系统:

                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);
    
    1 回复  |  直到 10 年前
        1
  •  2
  •   JvO Rajesh.k    10 年前

    事实上,是的。

    您已经准备好了大部分数据。我们只需要将其转换为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 *) 返回字符的大小 指针,指针 ,因此在第一行中,我们为 h 标题行+1。在将数组的第一行设置为标头后,我们将复制 img 内存块在剩余的“行”中,并将其馈送到QPixmap。之后我们就结束了。