我试图旋转一个图像,但它没有被旋转
本文关键字:旋转 图像 一个 | 更新日期: 2023-09-27 18:14:24
下面是我的代码:
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"));
}
我不知道怎么回事
您没有使用返回的新位图图像。将返回值保存为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()));
使用:
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"));