C# 我试图旋转图像,但它没有被旋转
这是我的密码:C# 我试图旋转图像,但它没有被旋转,c#,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 (
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;
}
我不知道怎么了 您尚未使用返回的新位图图像。 将返回值保存在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"));
}
即使返回旋转后的图像,也不会使用该图像 与此相反:
RotateImg(bit1, 100f, Color.FromName(colors.SelectedItem.ToString()));
使用:
然后使用新图像
在
您将如何处理返回的新图像。没有对此进行任何操作。除非这是您必须执行的分配,否则您可以使用.NET framework本身来使用和旋转位图。旁注:使用将
位图bit1=new…
包装到中,否则您将有资源泄漏<代码>使用(位图位1=new…{…}
RotateImg(bit1, 100f, Color.FromName(colors.SelectedItem.ToString()));
Bitmap newImage = RotateImg(bit1, 100f, Color.FromName(colors.SelectedItem.ToString()));
Rectangle r = new Rectangle(0,0,(int)newImage.Width, (int)newImage.Height);
newImage.Save(Server.MapPath("mydir/imgnew.jpg"));