我正在尝试旋转图像,但它没有被旋转

时间:2015-09-23 13:13:58

标签: c#

这是我的代码:

public static Bitmap RotateImg(Bitmap bmp, float angle, Color bkColor)
{
    angle = angle % 360;
    if (angle > 180)
        angle -= 360;

    System.Drawing.Imaging.PixelFormat pf = default(System.Drawing.Imaging.PixelFormat);
    if (bkColor == Color.Transparent)
    {
        pf = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
    }
    else
    {
        pf = bmp.PixelFormat;
    }

    float sin = (float)Math.Abs(Math.Sin(angle * Math.PI / 180.0)); // this function takes radians
    float cos = (float)Math.Abs(Math.Cos(angle * Math.PI / 180.0)); // this one too
    float newImgWidth = sin * bmp.Height + cos * bmp.Width;
    float newImgHeight = sin * bmp.Width + cos * bmp.Height;
    float originX = 0f;
    float originY = 0f;

    if (angle > 0)
    {
        if (angle <= 90)
            originX = sin * bmp.Height;
        else
        {
            originX = newImgWidth;
            originY = newImgHeight - sin * bmp.Width;
        }
    }
    else
    {
        if (angle >= -90)
        originY = sin * bmp.Width;
        else
        {
            originX = newImgWidth - sin * bmp.Height;
            originY = newImgHeight;
        }
    }

    Bitmap newImg = new Bitmap((int)newImgWidth, (int)newImgHeight, pf);
    Graphics g = Graphics.FromImage(newImg);
    g.Clear(bkColor);
    g.TranslateTransform(originX, originY); // offset the origin to our calculated values
    g.RotateTransform(angle); // set up rotate
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
    g.DrawImageUnscaled(bmp, 0, 0); // draw the image at 0, 0
    g.Dispose();

    return newImg;
}

我在这里使用它:

protected void btnRotateImg_Click(object sender, EventArgs e)
{
    Bitmap bit1 = new Bitmap(Server.MapPath("mydir/img.jpg"));
    Graphics gbit1 = Graphics.FromImage(bit1);
    RotateImg(bit1, 100f, Color.FromName(colors.SelectedItem.ToString()));
    Rectangle r = new Rectangle(0,0,(int)bit1.Width, (int)bit1.Height);
    bit1.Save(Server.MapPath("mydir/imgnew.jpg"));
}

我不知道什么是错的!..

2 个答案:

答案 0 :(得分:1)

您尚未使用返回的新位图图像。 将返回值保存在bit1中,然后使用它:

protected void btnRotateImg_Click(object sender, EventArgs e)
{
    Bitmap bit1 = new Bitmap(Server.MapPath("mydir/img.jpg"));
    Graphics gbit1 = Graphics.FromImage(bit1);
    bit1 = RotateImg(bit1, 100f,   Color.FromName(colors.SelectedItem.ToString())); // Modification here
    Rectangle r = new Rectangle(0,0,(int)bit1.Width, (int)bit1.Height);
    bit1.Save(Server.MapPath("mydir/imgnew.jpg"));
}

答案 1 :(得分:1)

即使您正在返回它,也没有使用旋转的图像

而不是:

RotateImg(bit1, 100f,   Color.FromName(colors.SelectedItem.ToString()));

使用:

Bitmap newImage = RotateImg(bit1, 100f,   Color.FromName(colors.SelectedItem.ToString()));

然后使用newImage 在

Rectangle r = new Rectangle(0,0,(int)newImage.Width, (int)newImage.Height);
    newImage.Save(Server.MapPath("mydir/imgnew.jpg"));