• 0

C# image percentage resize


Question

Hey everyone, I'm looking for a way to mathematically scale the image. I already have the image function written. I have also obtained the image size (width/height). But I need a way to make this function read in the width/height and find the percentage to scale to 190x123.

Here's my code so far (the 180 percent was just a test)

public static System.Drawing.Image ScaleByPercent(System.Drawing.Image imgPhoto, int Percent)
		{
			float nPercent = ((float)Percent / 100);

			int sourceWidth = (int)imgPhoto.Width;
			int sourceHeight = (int)imgPhoto.Height;
			int sourceX = 0;
			int sourceY = 0;

			int destX = 0;
			int destY = 0;
			int destWidth = (int)(sourceWidth * nPercent);
			int destHeight = (int)(sourceHeight * nPercent);

			Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
									 PixelFormat.Format24bppRgb);
			bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
									imgPhoto.VerticalResolution);

			Graphics grPhoto = Graphics.FromImage(bmPhoto);
			grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

			grPhoto.DrawImage(imgPhoto,
				new Rectangle(destX, destY, destWidth, destHeight),
				new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
				GraphicsUnit.Pixel);

			grPhoto.Dispose();
			return bmPhoto;
		}

My actual program

static void Main(string[] args)
		{
			Image imgPhotoV =
				Image.FromFile(@"C:\testimg.jpg");
			Image imgPhoto = null;

			int imgWidth = imgPhotoV.Width;
			int imgHeight = imgPhotoV.Height;

			System.Diagnostics.Debug.WriteLine(imgPhotoV.Width);
			System.Diagnostics.Debug.WriteLine(imgPhotoV.Height);
			imgPhoto = DRSImgResize.ScaleByPercent(imgPhotoV, 180);
			imgPhoto.Save(@"C:\imageresize_1.jpg", ImageFormat.Jpeg);
			imgPhoto.Dispose();
			Console.ReadLine();

		}

Any ideas?

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.