C++修改图片的尺寸

在设置用户头像的时候,从网络上下载下来的用户头像的尺寸可能和我们本身想要的头像的尺寸不一致,这时候我们就需要对用户头像的尺寸进行修改,下面直接给出代码,需要的朋友可以参考。

//改变图片的尺寸
bool ResizePicture(CString strSource, CString strTarget)
{
    int WIDTH = 70;
    int HEIGHT = 70;
    CImage oldimg;
    CImage newimg;
    oldimg.Load(strSource);
    if (oldimg.IsNull())
        return false;
    int nWidth = 0;
    int nHeight = 0;

    nWidth = oldimg.GetWidth();
    nHeight = oldimg.GetHeight();

    if (nWidth > WIDTH || nHeight > HEIGHT)
    {
        double dRatio = nWidth * 1.0 / nHeight;
        if (nWidth > nHeight)
        {
            nWidth = WIDTH;
            nHeight = (int)(nWidth / dRatio);
        }
        else
        {
            nHeight = HEIGHT;
            nWidth = (int)(nHeight * dRatio);
        }
    }

    if (!newimg.CreateEx(nWidth, nHeight, 24, BI_RGB))
    {
        oldimg.Destroy();
        return false;
    }

    int nPreMode = ::SetStretchBltMode(newimg.GetDC(), HALFTONE);
    newimg.ReleaseDC();
    oldimg.Draw(newimg.GetDC(), 0, 0, nWidth, nHeight, 0, 0, oldimg.GetWidth(), oldimg.GetHeight());
    newimg.ReleaseDC();
    ::SetBrushOrgEx(newimg.GetDC(), 0, 0, NULL);
    newimg.ReleaseDC();
    ::SetStretchBltMode(newimg.GetDC(), nPreMode);
    newimg.ReleaseDC();

    newimg.Save(strTarget);
    newimg.Destroy();
    oldimg.Destroy();

    return true;
}

你可能感兴趣的:(it)