C# 将位图旋转90度
我正在尝试使用以下函数将位图旋转 90 度。它的问题是,当高度和宽度不相等时,它会截掉部分图像。
请注意 returnBitmap width = original.height 和 height = original.width
任何人都可以帮助我解决这个问题或指出我做错了什么吗?
private Bitmap rotateImage90(Bitmap b)
{
Bitmap returnBitmap = new Bitmap(b.Height, b.Width);
Graphics g = Graphics.FromImage(returnBitmap);
g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
g.RotateTransform(90);
g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
g.DrawImage(b, new Point(0, 0));
return returnBitmap;
}
I'm trying to rotate a bitmap 90 degrees using the following function. The problem with it is that it cuts off part of the image when the height and width are not equal.
Notice the returnBitmap width = original.height and it's height = original.width
Can anyone help me solve this issue or point out what I'm doing wrong?
private Bitmap rotateImage90(Bitmap b)
{
Bitmap returnBitmap = new Bitmap(b.Height, b.Width);
Graphics g = Graphics.FromImage(returnBitmap);
g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
g.RotateTransform(90);
g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
g.DrawImage(b, new Point(0, 0));
return returnBitmap;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个怎么样:
What about this:
该错误出现在您第一次调用
TranslateTransform
中:此转换需要位于
returnBitmap
的坐标空间中,而不是b
中,因此应该是:或等效地
您的第二个
TranslateTransform
是正确的,因为它将在旋转之前应用。不过,正如 Rubens Farias 建议的那样,您可能最好使用更简单的
RotateFlip
方法。The bug is in your first call to
TranslateTransform
:This transform needs to be in the coordinate space of
returnBitmap
rather thanb
, so this should be:or equivalently
Your second
TranslateTransform
is correct, because it will be applied before the rotation.However you're probably better off with the simpler
RotateFlip
method, as Rubens Farias suggested.我遇到了,经过一点修改,我就让它工作了。我发现了一些其他的例子,并注意到缺少一些对我来说很重要的东西。我必须调用 SetResolution,如果不调用,图像最终的尺寸就会错误。我还注意到高度和宽度向后,尽管我认为无论如何对于非方形图像都会有一些修改。我想我会把这篇文章发布给任何遇到这个问题的人,就像我遇到同样的问题一样。
这是我的代码
I came across and with a little modification I got it to work. I found some other examples and noticed something missing that made the difference for me. I had to call SetResolution, if I didn't the image ended up the wrong size. I also noticed the Height and Width were backwards, although I think there would be some modification for a non square image anyway. I figured I would post this for anyone who comes across this like I did with the same problem.
Here is my code