C++图像缩放

VC++中自带的图像缩放函数两个:

1、

BOOL StretchBlt ( 
int x, 
int y, 
int nWidth, 
int nHeight, 
CDC* pSrcDC, 
int xSrc, 
int ySrc, 
int nSrcWidth, 
int nSrcHeight, 
DWORD dwRop ); 

2、

int StretchDIBits(
  HDC hdc,                      // handle to DC
  int XDest,                    // x-coord of destination upper-left corner
  int YDest,                    // y-coord of destination upper-left corner
  int nDestWidth,               // width of destination rectangle
  int nDestHeight,              // height of destination rectangle
  int XSrc,                     // x-coord of source upper-left corner
  int YSrc,                     // y-coord of source upper-left corner
  int nSrcWidth,                // width of source rectangle
  int nSrcHeight,               // height of source rectangle
  CONST VOID *lpBits,           // bitmap bits
  CONST BITMAPINFO *lpBitsInfo, // bitmap data
  UINT iUsage,                  // usage options
  DWORD dwRop                   // raster operation code
);
这两个函数的作用是将图像的一部分或全部复制到另一个框架里面去,如果新框架比原来的部分大,则将图像进行放大,否则缩小。(听说这两个函数缩放效果不好,容易引起图像失真)

自己编写图像缩放代码:
 int NewWidth=int(Width*fx+0.5);
int NewHeight=int(Height*fy+0.5);
int NewLineBytes=WIDTHBYTES(NewWidth*8);
HDIB hNewDIB=(HDIB)::GlobalAlloc(GHND,40+4*256+NewLineBytes*NewHeight);//分配句柄空间
if(hNewDIB==NULL) return;
LPBYTE lpDIBnew=(LPBYTE)::GlobalLock((HGLOBAL)hNewDIB);//由新句柄得到第二部分指针
memcpy(lpDIBnew,lpDIB,1064);//复制信息头和调色板
BYTE* lpDIBBitsnew=(BYTE*)(lpDIBnew+40+4*256);//得到第四部分指针
int i0,j0;//图像在原DIB中的座标
int i,j;//图像在新DIB中的座标
float m,n;
for(i=0;i<NewHeight;i++)//双线性插值
for(j=0;j<NewWidth;j++)
{
i0=(int)(i/fy+0.5);j0=(int)(j/fx+0.5);//计算该象素在原DIB中的座标
if((j0>=0)&&(j0<Width)&&(i0>=0)&&(i0<Height))//判断是否在原图像范围内
{
m=(float)(i/fy+0.5)-i0;n=(float)(j/fx+0.5)-(int)j0;
BYTE x1,x2,y1,y2;
x1=*(lpDIBBits+int(LineBytes*(Height-i0-1)+j0));
x2=*(lpDIBBits+int(LineBytes*(Height-i0-1)+j0+1));
y1=*(lpDIBBits+int(LineBytes*(Height-i0)+j0));
y2=*(lpDIBBits+int(LineBytes*(Height-i0)+j0+1));
*(lpDIBBitsnew+NewLineBytes*(NewHeight-i-1)+j)=(BYTE)((1-m)*(1-n)*x1+(1-m)*n*x2+m*(1-n)*y1+m*n*y2);
}
   else 
   *((unsigned char*)(lpDIBBitsnew+NewLineBytes*i+j))=255;//对于原图像中没有的像素,直接赋值为255
}

LPBITMAPINFOHEADER h=(LPBITMAPINFOHEADER)lpDIBnew;//获得指向新图像信息头的指针
h->biHeight=NewHeight;//更新信息头的信息
h->biWidth=NewWidth;
h->biSizeImage=NewWidth*NewHeight;
pDoc->hDib=hNewDIB;
pDoc->dWidth=NewWidth;pDoc->dHeight=NewHeight;
OnInitialUpdate();
Invalidate(TRUE);
delete dlg;

里面用到的是双线性内插法。(比最邻近法好,减少失真)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章