如何使用C#从URL下载时控制图像大小

时间:2014-07-18 03:43:48

标签: c# image download webclient-download

使用c#直接从URL下载图像时,有任何可能的方法来控制图像大小。我有使用此代码从URL下载的图像:

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

我的问题是我不希望图像宽度大于800px,如果宽度小于800px的图像大小无关紧要,应该按原始大小继续下载。但是如果图像宽度大于800px,我希望图像调整大小到最大宽度仅为800px。

1 个答案:

答案 0 :(得分:1)

  

但是如果图像宽度大于800px,我希望图像调整大小   最大宽度仅为800px。

您必须下载图片才能重新调整大小。下载图像并检查它是否具有更大的宽度,然后是您所需的宽度,然后您可以重新调整图像大小。这个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;
}