using System;
using System.Net;
using System.IO;
using System.Text;
using System.Drawing;
namespace ReduceImage
{
/// <summary>
/// 下载远程图片保存到本地地址
/// </summary>
public class Img
{
public static void ReduceImage(string imageFile, int toWidth, int toHeight)
{
try
{
Image originalImage = Image.FromFile(imageFile);
if (toWidth <= 0 && toHeight <= 0)
{
return;
}
else if (toWidth > 0 && toHeight > 0)
{
if (originalImage.Width < toWidth && originalImage.Height < toHeight)
return;
}
else if (toWidth <= 0 && toHeight > 0)
{
if (originalImage.Height < toHeight)
return;
toWidth = originalImage.Width * toHeight / originalImage.Height;
}
else if (toHeight <= 0 && toWidth > 0)
{
if (originalImage.Width < toWidth)
return;
toHeight = originalImage.Height * toWidth / originalImage.Width;
}
Image toBitmap = new Bitmap(toWidth, toHeight);
try
{
using (Graphics g = Graphics.FromImage(toBitmap))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(originalImage,
new Rectangle(0, 0, toWidth, toHeight),
new Rectangle(0, 0, originalImage.Width, originalImage.Height),
GraphicsUnit.Pixel);
originalImage.Dispose();
toBitmap.Save(imageFile, System.Drawing.Imaging.ImageFormat.Png);
toBitmap.Dispose();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (originalImage != null) originalImage.Dispose();
if (toBitmap != null) toBitmap.Dispose();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}