重新缩放图像会导致像素丢失

时间:2014-08-27 03:01:38

标签: c# winforms

我似乎无法升级8x8像素的图像。测试时,我想将图像缩放到64x64像素。但是,这样做的结果是:

Result of scale

按照我下面的方式重新调整它,顶部删除4个像素高度,左侧删除4个像素宽度,底部增加4个黑色像素高度,右侧增加4个像素宽度。

以下是我用来重新缩放图片的代码:

private static Image ScaleImage(string username, int size)
{
    Image avatar = MergeImage(username);

    int originalWidth = avatar.Width;
    int originalHeight = avatar.Height;

    float ratioX = (float)size / (float)originalWidth;
    float ratioY = (float)size / (float)originalHeight;
    float ratio = Math.Min(ratioX, ratioY);

    int newWidth = (int)(originalWidth * ratio);
    int newHeight = (int)(originalHeight * ratio);

    Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format48bppRgb);

    using (Graphics g = Graphics.FromImage(newImage))
    {
        g.InterpolationMode = InterpolationMode.NearestNeighbor;
        g.DrawImage(avatar, 0, 0, newWidth, newHeight);
    }

    return newImage;
}

我不确定这里出了什么问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

g.DrawImage

之前添加此内容
g.PixelOffsetMode = PixelOffsetMode.Half;