通过QT将二维数组中的像素点显示成一张图片


从文件42.train读入一个长度为dstSize*dstSize字节数据,存到一个数组psData中,这些数据全部是像素点的值,不包括文件头等辅助信息.通过qt创建一个gui工程,基类选择QWidegt,将图片显示出来。

代码如下:

#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <cstdio>
typedef unsigned short WORD;
typedef unsigned char BYTE;
typedef unsigned int DWORD;
const int dstSize = 128;

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}
void Widget::paintEvent(QPaintEvent *e)
{
    QPainter paint(this);
    FILE *pf = NULL;
    const char * name = "42.train";
    DWORD wsize = dstSize * dstSize;
    BYTE * psData = (BYTE*)malloc(wsize);
    if( (pf = fopen(name,  "rb" )) == NULL )
    {
        printf( "File coulkd not be opened " );
        return ;
    }
    DWORD *pSrc = (DWORD*)malloc(wsize*sizeof(DWORD));
    int n = fread(psData, wsize, 1, pf);
    if( n== 1)
    {
        for (unsigned int i = 0; i < wsize; ++i)
        {
            BYTE *pb=(BYTE *)(pSrc+i);
            pSrc[i] = 0;
            pb[0] = psData[i];
            pb[1] = psData[i];
            pb[2] = psData[i];
        }
        free(psData);
    }

    QByteArray imageByteArray = QByteArray( (const char*)pSrc,  wsize*4 );
    uchar*  transData = (unsigned char*)imageByteArray.data();
    QImage image = QImage(transData, dstSize, dstSize, QImage::Format_RGB32);
    free(pSrc);
    fclose(pf);
    paint.drawImage(QPoint(0, 0), image);
    paint.end();
}

相关内容