Image AutoRotate Feature using .Net

23 Views Asked by At

Have a requirement to autorotate images that are being scanned . I have to implement it via .Net /C# .Is there any paid or free libraries to accomplish it?

1

There are 1 best solutions below

1
Jalpesh Vadgama On

You can do something like following

private Bitmap RotateBitmap(Bitmap bm, float angle)
{ 
  // Make a Matrix to represent rotation
  // by this angle.
  Matrix rotate_at_origin = new Matrix();
  rotate_at_origin.Rotate(angle);

   // Rotate the image's corners to see how big
   // it will be after rotation.
   PointF[] points =
   {
       new PointF(0, 0),
       new PointF(bm.Width, 0),
       new PointF(bm.Width, bm.Height),
       new PointF(0, bm.Height),
    };
    rotate_at_origin.TransformPoints(points);
    float xmin, xmax, ymin, ymax;
    GetPointBounds(points, out xmin, out xmax,
     out ymin, out ymax);

    // Make a bitmap to hold the rotated result.
    int wid = (int)Math.Round(xmax - xmin);
    int hgt = (int)Math.Round(ymax - ymin);
    Bitmap result = new Bitmap(wid, hgt);

    // Create the real rotation transformation.
    Matrix rotate_at_center = new Matrix();
    rotate_at_center.RotateAt(angle,
    new PointF(wid / 2f, hgt / 2f));

    // Draw the image onto the new bitmap rotated.
    using (Graphics gr = Graphics.FromImage(result))
    {
      // Use smooth image interpolation.
       gr.InterpolationMode = InterpolationMode.High;

      // Clear with the color in the image's upper left corner.
      gr.Clear(bm.GetPixel(0, 0));

      //// For debugging. (It's easier to see the background.)
      //gr.Clear(Color.LightBlue);

      // Set up the transformation to rotate.
      gr.Transform = rotate_at_center;

      // Draw the image centered on the bitmap.
      int x = (wid - bm.Width) / 2;
      int y = (hgt - bm.Height) / 2;
       gr.DrawImage(bm, x, y);
  }

  // Return the result bitmap.
  return result;

}

Here is the full article for that - Rotate Images with C#