I am fairly new to C# GDI+ graphics.
I want to draw an image over another, which should be centered horizontally and vertically in a fixed height and width container on an image.
I tried to do this with horizontal centering and the output is weird.
I am sharing the commented code of how I am trying to do it, let me know if there is any easier way to do it, I just want to scale and center the image.
//The parent image resolution is 4143x2330
//the container for child image is 2957x1456
Image childImage = Image.FromFile(path.Text.Trim());
Image ParentImage = (Image)EC_Automation.Properties.Resources.t1;
Bitmap bmp2 = (Bitmap)ParentImage;
Graphics graphic = Graphics.FromImage(ParentImage);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
double posX = (2957 / 2.0d) - (childImage.Width / 2.0d);
//HAlf of the container size - Half of the image size should make it center in container
graphic.DrawImage((Image)childImage,
new Rectangle(new Point((int)posX, 420), new Size( 2957, 1456))); //Drawing image
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
To center an image with CSS Grid, wrap the image in a container div element and give it a display of grid . Then set the place-items property to center. P.S.: place-items with a value of center centers anything horizontally and vertically.
To center an image, we have to set the value of margin-left and margin-right to auto and make it a block element by using the display: block; property. If the image is in the div element, then we can use the text-align: center; property for aligning the image to center in the div.
"display:inline-block" on the IMG. And remove the float and position statements. Then "text-align:center" for the container div. I used a div as a fake img but it should work the same.
public Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(maxWidth, maxHeight);
using (var graphics = Graphics.FromImage(newImage))
{
// Calculate x and y which center the image
int y = (maxHeight/2) - newHeight / 2;
int x = (maxWidth / 2) - newWidth / 2;
// Draw image on x and y with newWidth and newHeight
graphics.DrawImage(image, x, y, newWidth, newHeight);
}
return newImage;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With