这里是我的代码:我试图旋转图像,但它没有被旋转
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"));
}
我不知道什么是错..
你在做什么与返回的新图像。对此没有做任何事情。 – Codeek
除非您需要执行此任务,否则您可以使用https://msdn.microsoft.com/zh-CN/library/system.drawing.image.rotateflip(v=vs.110).aspx和https: //msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.rotation(v=vs.110).aspx使用.NET框架本身来旋转您的位图。 – displayName