c#中旋转图片可以剪切图片
本文关键字:旋转 | 更新日期: 2023-09-27 18:03:38
我正在尝试用c#旋转图片,并使用以下代码:
///create a new empty bitmap to hold rotated image
Bitmap returnBitmap = new Bitmap(newBMP.Width, newBMP.Height);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(returnBitmap);
//move rotation point to center of image
g.TranslateTransform((float)newBMP.Width / 2, (float)newBMP.Height / 2);
//rotate
g.RotateTransform(-90);
//move image back
g.TranslateTransform(-(float)newBMP.Width / 2, -(float)newBMP.Height / 2);
//draw passed in image onto graphics object
g.DrawImage(newBMP, new Point(0, 0));
newBMP
是一个位图,我从一个形式,我正在改变它的大小。然后我想旋转它,但是当我尝试上面的代码时,它切断了图片的顶部和底部。完成所有这些操作后,我将新图片保存在服务器上。
所有工作正常,除了旋转…
有人看到问题了吗?
解决我用了这个:c#旋转位图90度
如果位图的宽度大于高度,当你旋转它90度时,你会得到裁剪。当你调用g.TranslateTranform
的时候,你需要把这个考虑进去。
这个答案是刚刚回答(对于任何角度)的vb.net堆栈溢出…
如何使用图形旋转JPEG。不带剪辑的RotateTransform
应该很容易转换为c#
public static Bitmap RotateImage(Bitmap image, float angle)
{
//create a new empty bitmap to hold rotated image
double radius = Math.Sqrt(Math.Pow(image.Width, 2) + Math.Pow(image.Height, 2));
Bitmap returnBitmap = new Bitmap((int)radius, (int)radius);
//make a graphics object from the empty bitmap
using (Graphics graphic = Graphics.FromImage(returnBitmap))
{
//move rotation point to center of image
graphic.TranslateTransform((float)radius / 2, (float)radius / 2);
//rotate
graphic.RotateTransform(angle);
//move image back
graphic.TranslateTransform(-(float)image.Width / 2, -(float)image.Height / 2);
//draw passed in image onto graphics object
graphic.DrawImage(image, new Point(0, 0));
}
return returnBitmap;
}