【问题标题】:image rotation with white background白色背景的图像旋转
【发布时间】:2013-06-25 06:11:39
【问题描述】:

我想这对于那些经常使用 GDI 的人来说是相当简单的。我有一个要旋转的图像。

示例图片:

应用轮换后,它看起来如下:

这是使用的代码:

public Bitmap RotateBitmap(Bitmap bitmap, float angle)
{
    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        graphics.TranslateTransform((float)bitmap.Width / 2, (float)bitmap.Height / 2);
        graphics.RotateTransform(angle);
        graphics.TranslateTransform(-(float)bitmap.Width / 2, -(float)bitmap.Height / 2);
        graphics.DrawImage(bitmap, new Point(0, 0));
    }
    return bitmap;
}

我想去掉的是旋转前图像中保留的部分。在调用DrawImage 之前使用DrawRectangleClear 的任何尝试都会给我白色图像,这有点道理。

【问题讨论】:

    标签: c# gdi+ image-rotation


    【解决方案1】:

    尝试以下方法:

    public Bitmap RotateBitmap(Image bitmap, float angle) {
        Bitmap result = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat);
        using(Graphics graphics = Graphics.FromImage(result)) {
            graphics.TranslateTransform((float)bitmap.Width / 2f, (float)bitmap.Height / 2f);
            graphics.RotateTransform(angle);
            graphics.TranslateTransform(-(float)bitmap.Width / 2f, -(float)bitmap.Height / 2f);
            graphics.DrawImage(bitmap, Point.Empty);
        }
        return result;
    }
    

    【讨论】:

    • 我试过了,result 仍然包含未旋转的图像。
    • @SebastianEdelmeier 请再次检查我的代码 - 此代码将旋转图像绘制到新位图中。它按我的预期工作。
    • 对不起,我的错!你完全正确 - 它按预期工作!