函数Draw主要用来显示PNG图像对应的位图图像,通过指定宽度和高度,可实现图像的缩放显示。该函数主要为VC++应用程序编写。
BOOL MyPNG::Draw(CDC *pDC, int nX, int nY, int nWidth, int nHeight)
{ if( nWidth == -1 ) nWidth = cxImgSize; if( nHeight == -1 ) nHeight= cyImgSize;
StretchDIBits( pDC->m_hDC, nX, nY,nWidth, nHeight,0, 0,cxImgSize, cyImgSize,pPixelBuffer,&m_bmi, BI_RGB, SRCCOPY );
return true;
}
成员函数FillBitmapInfo的功能是根据PNG图像大小设置位图信息,为显示图像做准备。
bool MyPNG::FillBitmapInfo() //给变量m_bmi(位图信息头)赋值
{
m_bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
m_bmi.bmiHeader.biHeight=cyImgSize; m_bmi.bmiHeader.biWidth=cxImgSize;
m_bmi.bmiHeader.biPlanes = 1; m_bmi.bmiHeader.biBitCount = 24;
m_bmi.bmiHeader.biCompression = 0;
return true;
}
成员函数PngToBitmap主要实现将PNG图像数据转换成位图图像数据。
bool MyPNG::PngToBitmap()
{
BYTE *src, *dst; BYTE r, g, b, a;
const int cDIChannels = 3; WORD wDIRowBytes;
int xImg, yImg;
if (pPixelBuffer!=NULL) { delete pPixelBuffer; pPixelBuffer=NULL; }//空间已分配则先释放
wImgRowBytes = cImgChannels * cxImgSize;//每行的字节数
wDIRowBytes = (WORD) ((cDIChannels * cxImgSize + 3L) >> 2) << 2;
pPixelBuffer=new BYTE[wDIRowBytes*cyImgSize]; //分配内存空间
if (pPixelBuffer==NULL) { AfxMessageBox("PNG to Bitmap:Out of memory."); return false;} //分配失败则返回
for (yImg = 0; yImg < cyImgSize; yImg++) // 拷贝图像数据
{ src = pbImage + yImg * wImgRowBytes;
dst = pPixelBuffer + (cyImgSize - yImg - 1) * wDIRowBytes ;//+ cxImgPos * cDIChannels;
for (xImg = 0; xImg < cxImgSize; xImg++)
{ r = *src++; g = *src++; b = *src++;
*dst++ = b; *dst++ = g; *dst++ = r; //位图的次序为BGR,PNG的次序为RGB
if (cImgChannels == 4) { a = *src++; } //通道信息跳过
}
}
return true;
}
|