Search code examples
c#winformsgdi+autoresize

Center image on another image


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 

Solution

  • Solved it , I was drawing the image of fixed width, whereas it should have been with a new width based on the aspect ratio and new height,

    Also I was taking trying to find the center of the image from Container, which should have been the center of the whole parent Image