1

我有一个 unsigned char 数组,它的定义如下:

unsigned char **chars = new unsigned char *[H];
for(int i = 0; i < H; i++)
{

    chars[i] = new unsigned char[W*3];
}

其中 H 是图像的高度,W 是宽度,并且 chars 填充在该函数的其余部分中,循环遍历输入图像的行 x 列。字符按红绿蓝的顺序填充

我试图用这样的东西来阅读它:

QImage *qi = new QImage(imwidth, imheight, QImage::Format_RGB888);
    for (int i = 0 ; i < imheight ; i++)
        for (int j = 0 ; j < imwidth ; j++)
        {      //not sure why, but have to flip j and i in the index for setPixel
               qi->setPixel(j,i,qRgb(imageData[i][j],imageData[i][j+1],imageData[i][j+2]));
               j+=3;

           }

   QPixmap p(QPixmap::fromImage(*qi,Qt::AutoColor));
   QPixmap p1(p.scaled(ui->menuBar->width(),ui->menuBar->width(), Qt::KeepAspectRatio, Qt::SmoothTransformation ));
   ui->viewLabel->setPixmap(p1);
   ui->viewLabel->setFixedHeight(p1.height());
   ui->viewLabel->setFixedWidth(p1.width());

其中 chars 在 imageData 数组中被返回给这个调用函数。

我究竟做错了什么?我是否应该使用不同的格式,即使我清楚地为每个像素分配了 3 个无符号字符(这就是我选择 RGB888 格式的原因)。发布的此代码返回图像,但显示不正确 - 部分乱码、褪色等

谢谢

4

1 回答 1

4

您可以直接从数据块创建QImage,而无需复制每个像素。

Since your image is stored with separate rows, you need something like

QImage image = new QImage(width,height,QImage::RGB888)

for (int h=0;h<height;h++) {
    // scanLine returns a ptr to the start of the data for that row
    memcpy(image.scanLine(h),chars[h],width*3);
}

if you use RGB32 then you need to manually set the alpha channel for each pixel to 0xff - just memset() the entire data to 0xff first

于 2011-01-19T00:35:34.480 回答