If I rotate a bitmap and want to keep track of a point on the original image as translated on the new image, how would I achieve this. I essentially want to know where the top right corner of the original image is on the new rotated and expanded image, so I can draw to a graphics surface in the correct location. I’m using the following code to rotate the bitmap (originally taken from another post).
public static Bitmap RotateImage(Bitmap origBmp, float angle)
{
Matrix matrix = new Matrix();
matrix.Translate(origBmp.Width / -2, origBmp.Height / -2, MatrixOrder.Append);
matrix.RotateAt(angle, new Point(0, 0), MatrixOrder.Append);
using (GraphicsPath graphicsPath = new GraphicsPath())
{
// Transform image points by rotation matrix
graphicsPath.AddPolygon(new Point[]
{
new Point(0, 0),
new Point(origBmp.Width, 0),
new Point(0, origBmp.Height)
});
graphicsPath.Transform(matrix);
PointF[] pts = graphicsPath.PathPoints;
Rectangle boundingBox = BoundingBox(origBmp, matrix);
Bitmap bmpDest = new Bitmap(boundingBox.Width, boundingBox.Height);
using (Graphics graphicsDest = Graphics.FromImage(bmpDest))
{
Matrix matrixDest = new Matrix();
matrixDest.Translate(bmpDest.Width / 2, bmpDest.Height / 2, MatrixOrder.Append);
graphicsDest.Transform = matrixDest;
graphicsDest.DrawImage(origBmp, pts);
}
return bmpDest;
}
}
private static Rectangle BoundingBox(
Image img,
Matrix matrix)
{
GraphicsUnit gu = new GraphicsUnit();
Rectangle imgRect = Rectangle.Round(img.GetBounds(ref gu));
// Transform the four points of the image, to get the resized bounding box.
Point topLeft = new Point(imgRect.Left, imgRect.Top);
Point topRight = new Point(imgRect.Right, imgRect.Top);
Point bottomRight = new Point(imgRect.Right, imgRect.Bottom);
Point bottomLeft = new Point(imgRect.Left, imgRect.Bottom);
Point[] points = new Point[]
{
topLeft,
topRight,
bottomRight,
bottomLeft
};
GraphicsPath graphicsPath = new GraphicsPath(
points,
new byte[]
{
(byte)PathPointType.Start,
(byte)PathPointType.Line,
(byte)PathPointType.Line,
(byte)PathPointType.Line
});
graphicsPath.Transform(matrix);
return Rectangle.Round(graphicsPath.GetBounds());
}
I’ve attempted to use the same translation approach to translate the point on the original image, but with no luck.
Chris Gedling is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.