向世明visual c++数字图像与图形处理中利用SetBitmapBits()函数设置指定区域的位数据,请问其中的有效宽度和高度是什么意思?或者说为什么这样来算?谢谢了
//设置DDB所使用的像素数据----局部
//x, y, nWidth, nHeight
//lpBits----数据源, 扫描宽度字节数必须是2的倍数
DWORD CDdb::SetBitmapBits(int x, int y, int nWidth, int nHeight, int nBitCount, LPBYTE lpbyBits)
{
ASSERT(lpbyBits); 
//类型不匹配, 则返回0, 表示没有设置任何数据
if(nBitCount != m_nBitCount)return 0; 

//进行参数合法性检测
if((x > m_nWidth - 1) || (y > nHeight - 1))
{
AfxMessageBox("Cross the border!"); 
return 0; 
}
有效宽度和高度:w , h
LONG w = (LONG)min(nWidth, m_nWidth - x); 
LONG h = (LONG)min(nHeight, m_nHeight - y); 

//扫描宽度, 以字节为单位, 必须被2整除
DWORD dwScanLength = CalcDdbWidthBytes(nWidth, nBitCount);  //实际拷贝的行字节长度:
DWORD dwLength = w; 
//数据偏移量
DWORD dwOffset = x; 
if(nBitCount == 16)
{
dwLength = w + w; 
dwOffset = x + x; 
}
else if(nBitCount == 24)
{
dwLength = 3 * w; 
dwOffset = 3 * x;  
}
else if(nBitCount == 32)
{
dwLength = 4 * w; 
dwOffset = 4 * x; 
} //指向与CDdb对象绑连的数据区
BYTE* pbyDdbDst = m_pDdbData + y * m_nDdbWidthBytes + dwOffset; 

//指向源数据的指针, 从外部而来
BYTE* pbyDdbRsc = lpbyBits; 

for(int i = 0; i < h; i++)
{
::CopyMemory(pbyDdbDst, pbyDdbRsc, dwLength); 
pbyDdbRsc += dwScanLength;  //from
pbyDdbDst += m_nDdbWidthBytes;  //to
}
m_pDdb->SetBitmapBits(m_nDdbWidthBytes * m_nHeight, m_pDdbData); 
return (nWidth * nHeight * nBitCount); 

解决方案 »

  1.   

    m_nWidth-x 〉 nWidth 可以保证不越界.
    反过来写就是x+nWidth <m_nWidth
      

  2.   

    template<class T>
        const T& min(const T& x, const T& y);
    template<class T, class Pred>
        const T& min(const T& x, const T& y, Pred pr);
    The first template function returns y if y < x. Otherwise it returns x. T need supply only a single-argument constructor and a destructor.
      

  3.   

    你想象一下,原图  左边是0  右边是m_nwidth
    矩形的左边是 x,右边是  x + nWidth
    左边肯定不会越界
    右边一定要保证 m_nwidth〉 x + nWidth