從文件42.train讀入一個長度為dstSize*dstSize字節數據,存到一個數組psData中,這些數據全部是像素點的值,不包括文件頭等輔助信息.通過qt創建一個gui工程,基類選擇QWidegt,將圖片顯示出來。代碼如下
[cpp] #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();
}
#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();
}