Ifwat
Ifwat

Reputation: 1553

How to control image size while download from URL using C#

there is has any possible way to control the image size while download the image directly from URL using c#. I have image that download from URL by using this code:

webClient.DownloadFile("remoteFileUrl", "localFilePath");

My problem is I do not want that image width to large that over than 800px, if image size of width smaller than 800px doesn't matter and should keep download by the original size. But if the image width is larger than 800px I want the image resize to maximum width is 800px only.

Upvotes: 1

Views: 1339

Answers (1)

Adil
Adil

Reputation: 148120

But if the image width is larger than 800px I want the image resize to maximum width is 800px only.

You have to download the image in order to re-size. Download the image and check if it has larger width then your required width then you can re-size image. This article explains it very well, that following re-size method is also take from the mentioned article.

private static Image resizeImage(Image imgToResize, Size size)
{
   int sourceWidth = imgToResize.Width;
   int sourceHeight = imgToResize.Height;

   float nPercent = 0;
   float nPercentW = 0;
   float nPercentH = 0;

   nPercentW = ((float)size.Width / (float)sourceWidth);
   nPercentH = ((float)size.Height / (float)sourceHeight);

   if (nPercentH < nPercentW)
      nPercent = nPercentH;
   else
      nPercent = nPercentW;

   int destWidth = (int)(sourceWidth * nPercent);
   int destHeight = (int)(sourceHeight * nPercent);

   Bitmap b = new Bitmap(destWidth, destHeight);
   Graphics g = Graphics.FromImage((Image)b);
   g.InterpolationMode = InterpolationMode.HighQualityBicubic;

   g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
   g.Dispose();

   return (Image)b;
}

Upvotes: 1

Related Questions