Last active
December 10, 2015 17:28
-
-
Save riyadparvez/4467802 to your computer and use it in GitHub Desktop.
A class for rotating bitmap image. It rotates image based on given rectangle without losing any information and giving white background to newly added region.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ImageRotator | |
{ | |
private readonly Bitmap image; | |
private double angle; | |
public Image OriginalImage | |
{ | |
get { return image; } | |
} | |
private ImageRotator(Bitmap image) | |
{ | |
this.image = image; | |
} | |
private double GetRadian(double degree) | |
{ | |
return degree * Math.PI / (double)180; | |
} | |
private Size CalculateSize(double angle) | |
{ | |
double radAngle = GetRadian(angle); | |
int width = (int)(image.Width * Math.Cos(radAngle) + image.Height * Math.Sin(radAngle)); | |
int height = (int)(image.Height * Math.Cos(radAngle) + image.Width * Math.Sin(radAngle)); | |
return new Size(width, height); | |
} | |
private PointF GetTopCoordinate(double radAngle) | |
{ | |
Bitmap image = CurrentlyViewedMappedImage.BitmapImage; | |
double topX = 0; | |
double topY = 0; | |
if (radAngle > 0) | |
{ | |
topX = image.Height * Math.Sin(radAngle); | |
} | |
if (radAngle < 0) | |
{ | |
topY = image.Width * Math.Sin(-radAngle); | |
} | |
return new PointF((float)topX, (float)topY); | |
} | |
public ImageRotator AngleEequals(double angle) | |
{ | |
this.angle = angle; | |
return this; | |
} | |
public Bitmap RotateImage(double angle) | |
{ | |
SizeF size = CalculateSize(radAngle); | |
Bitmap rotatedBmp = new Bitmap((int)size.Width, (int)size.Height); | |
Graphics g = Graphics.FromImage(rotatedBmp); | |
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; | |
g.CompositingQuality = CompositingQuality.HighQuality; | |
g.SmoothingMode = SmoothingMode.HighQuality; | |
g.PixelOffsetMode = PixelOffsetMode.HighQuality; | |
g.TranslateTransform(topPoint.X, topPoint.Y); | |
g.RotateTransform(GetDegree(radAngle)); | |
g.DrawImage(image, new RectangleF(0, 0, size.Width, size.Height)); | |
g.Dispose(); | |
return rotatedBmp; | |
} | |
public static class Builder | |
{ | |
public static ImageRotator CreateInstance(Image image) | |
{ | |
if(image == null) | |
{ | |
throw new ArgumentNullException("image"); | |
} | |
ImageRotator rotator = new ImageRotator(image as Bitmap); | |
return rotator; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment