Here we center an image in a Bitmap:
- We fit the width to the width of the Bitmap.
- We fit the height to the height of the Bitmap.
- We fit the width and height but do not allow the source image
to increase in size.
[C#]
using (Image image = Bitmap.FromFile(Server.MapPath("rez/david-bruyndonckx-F_hft1Wiyj8-unsplash.jpg"))) {
foreach (FitType fit in new FitType[] { FitType.Width, FitType.Height, FitType.WidthAndHeightNoEnlargement }) {
using (Bitmap bm = new Bitmap(640, 480)) {
using (Graphics graphics = Graphics.FromImage(bm)) {
graphics.Clear(Color.DeepSkyBlue);
RectangleF rect = RectangleF.FitIn(bm.Bounds, image.Bounds, fit);
graphics.DrawImage(image, rect);
}
bm.Save(Server.MapPath($"IG8_RectangleF_FitIn_{fit}.png"));
}
}
}

david-bruyndonckx-F_hft1Wiyj8-unsplash.jpg

IG8_RectangleF_FitIn_Width.png

IG8_RectangleF_FitIn_Height.png

IG8_RectangleF_FitIn_WidthAndHeightNoEnlargement.png
|