15,979
社区成员
发帖
与我相关
我的任务
分享
// 取得图片平均颜色
bool GetAverageColor(CDC *pDC, CBitmap &bitmap, const CSize &sizeImage, COLORREF &clrImage)
{
bool bIsResult = false;
CDC TempDC;
TempDC.CreateCompatibleDC(pDC);
CBitmap *pOldBitmap = TempDC.SelectObject(&bitmap);
int nWidth = sizeImage.cx;
int nHeight = sizeImage.cy;
// 定义位图信息
BITMAPINFO bi;
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
bi.bmiHeader.biWidth = nWidth;
bi.bmiHeader.biHeight = nHeight;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biSizeImage = nWidth * nHeight * 4; // 32 bit
bi.bmiHeader.biClrUsed = 0;
bi.bmiHeader.biClrImportant = 0;
// 获取位图数据
BYTE* pBits = (BYTE*)new BYTE[bi.bmiHeader.biSizeImage];
::ZeroMemory(pBits, bi.bmiHeader.biSizeImage);
int nLine = ::GetDIBits(TempDC.m_hDC, (HBITMAP)bitmap.GetSafeHandle(), 0, nHeight, pBits, &bi, DIB_RGB_COLORS);
if (!nLine)
{
delete []pBits;
pBits = NULL;
}
else
{
long r = 0, g = 0, b = 0;
for (LONG i = 0; i < nWidth; i++)
{
for (LONG j = 0; j < nHeight; j++)
{
b += pBits[(j * nWidth + i) * 4];
g += pBits[(j * nWidth + i) * 4 + 1];
r += pBits[(j * nWidth + i) * 4 + 2];
}
}
delete []pBits;
pBits = NULL;
int n = nWidth * nHeight;
clrImage = RGB(r / n, g / n, b / n);
bIsResult = true;
}
TempDC.SelectObject(pOldBitmap);
TempDC.DeleteDC();
return bIsResult;
}