只需创建一个函数:
/// <summary>
/// function to reduce image size and returns local path of image
/// </summary>
/// <param name="scaleFactor"></param>
/// <param name="sourcePath"></param>
/// <param name="targetPath"></param>
/// <returns></returns>
private string ReduceImageSize(double scaleFactor, Stream sourcePath, string targetPath)
{
try
{
using (var image = System.Drawing.Image.FromStream(sourcePath))
{
//var newWidth = (int)(image.Width * scaleFactor);
//var newHeight = (int)(image.Height * scaleFactor);
var newWidth = (int)1280;
var newHeight = (int)960;
var thumbnailImg = new System.Drawing.Bitmap(newWidth, newHeight);
var thumbGraph = System.Drawing.Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);
return targetPath;
}
}
catch (Exception e)
{
Console.WriteLine("Exception in ReduceImageSize" + e);
return "";
}
}
然后在你的 else 块中调用这个函数,如下所示,你将得到相同的图像,尺寸减小:
string ImageLink = "https://imagesus-ssl.homeaway.com/mda01/337b3cbe-80cf-400a-aece-c932852eb929.1.10";
string FinalTargetPath=@"F:\ReducedImage.png";
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(ImageLink);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
string ImagePath= ReduceImageSize(0.5, responseStream, FinalTargetPath);