使用GDI+缩放图片文件

 

总结一下个人所知道的使用GDI+缩放图片的方法.

 

方法一:最简单的,使用GetThumbnailImage,这个方法的局限性对支持内嵌缩略图的图片文件无效. 因为MSDN中提到:如果图片文件有内嵌的缩略图,那么就提取这个缩略图返回,否则就缩放原图片,不过我想对位图还是安全的:

Bitmap * image = new Bitmap(L"MagicLinux.bmp");

Image* pScaledImage = NULL;

UINT nWidth = image->GetWidth()/2;

UINT nHeight= image->GetHeight()/2;

pScaledImage = image->GetThumbnailImage(nWidth, nHeight, NULL, NULL);

delete pScaledImage;

delete image;

 

方法二,使用Graphics::DrawImage,这样还可以控制InterpolationMode(插值模式,在缩放和旋转时候使用),即可以控制缩放质量高低.也可以通过Graphics对象做其他的控制.

方法也比较简单,但是却费了我好久时间才研究出来,没办法,不熟悉GDI+,MSDN中翻来翻去,:)

Bitmap * ScaleBitmap(Bitmap * pBitmap,UINT nWidth,UINT nHeight)

{

Bitmap * pTemp = new Bitmap(nWidth,nHeight,pBitmap->GetPixelFormat());

if( pTemp )

{

Graphics * g = Graphics::FromImage(pTemp);

if( g )

{

// use the best interpolation mode

g->SetInterpolationMode(InterpolationModeHighQualityBicubic);

g->DrawImage(pBitmap,0,0,nWidth,nHeight);

delete g;

}

}

return pTemp;

}

pScaledImage = ScaleBitmap(image,nWidth,nHeight);

 

方法三,是从Codeguru上一个帖子上看到,和方法二类似,但是用了GDI的东东,我试了试,没成功,得到的是一幅黑图片,可能的原因是Bitmap::FromHBITMAP的第二个参数设置不对

原文代码如下:

Bitmap * bitmap = new Bitmap(TempBuf); // Create the bitmap

HDC Screen = GetDC(WindowVars.Handle);

piTemp->hdc = CreateCompatibleDC(Screen); // Create a memory DC

HBITMAP hbitmap;

if (bStretchPictures)

hbitmap = CreateCompatibleBitmap(Screen, Size.X, Size.Y);

else

hbitmap = CreateCompatibleBitmap(Screen, bitmap->GetWidth(), bitmap->GetHeight());

SelectObject(piTemp->hdc, hbitmap); // Initialize the DC

Graphics * graphics = new Graphics(piTemp->hdc); // Create the Graphics class

if (bStretchPictures)

graphics->DrawImage(bitmap, 0, 0, Size.X, Size.Y); // Draw the scaled image

else

graphics->DrawImage(bitmap, 0, 0, bitmap->GetWidth(), bitmap->GetHeight());

ReleaseDC(WindowVars.Handle, Screen);

delete graphics;

delete bitmap;

 

 

另外再补上保存图片的代码:

 

bool SaveAsImageFile(Image * pImage,LPCWSTR lpszFileName,LPCWSTR lpszImageType)

{

 

UINT num = 0;

 

// number of image encoders

UINT size = 0;

 

// size of the image encoder array in bytes

ImageCodecInfo* pImageCodecInfo = NULL;

 

if(GetImageEncodersSize(&num, &size)!= Ok || size == 0 )

return false; // Failure

 

pImageCodecInfo = (ImageCodecInfo*)(malloc(size));

if(pImageCodecInfo == NULL)

return false; // Failure

 

if(GetImageEncoders(num, size, pImageCodecInfo)!= Ok )

return false;

 

bool bOk = false;

for(UINT j = 0; j < num; ++j)

{

if( wcscmp(pImageCodecInfo[j].MimeType, lpszImageType) == 0 )

{

pImage->Save(lpszFileName,&(pImageCodecInfo[j].Clsid));

bOk = true;

break;

}

 

}

 

free(pImageCodecInfo);

return bOk;

 

}

 

调用象这样就可以保存成各种图片(当然要求有对应的encoder才行):

SaveAsImageFile(pScaledImage,L"1.bmp",L"image/bmp");

SaveAsImageFile(pScaledImage,L"1.jpg",L"image/jpeg");

SaveAsImageFile(pScaledImage,L"1.png",L"image/png");

你可能感兴趣的:(使用GDI+缩放图片文件)