等比例压缩图片

最近在开发图片网站,在网上找了很多图片等比例缩放,但是没有一个可以随意发挥!苦闷中。。。所以我特写了通用的 图片缩放 希望大家喜欢!

该段程序我就不注释了,我只把参数说一下:

sourcePath:要缩放图片路径

savePath: 缩放后图片路径

w:最大的宽度

h:最大的高度

如果有问题,可以留言 chocas.zhang@msn.com

using System;
using System. Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
/// <summary>
///ImageNew 的摘要说明
/// </summary>
namespace ImageCut
{
public class ImageNew
{
public ImageNew()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public static void ImageChange(string sourcePath, string savePath, int w, int h)
{
System.Drawing.Image _sourceImg = System.Drawing.Image.FromFile(sourcePath);
double _newW = (double)w, _newH = (double)h, t;
if ((double)_sourceImg.Width > w)
{
t = (double)w;
}
else
{
t = (double)_sourceImg.Width;
}

if ((double)_sourceImg.Height * (double)t / (double)_sourceImg.Width > (double)h)
{
_newH = (double)h;
_newW = (double)h / (double)_sourceImg.Height * (double)_sourceImg.Width;
}
else
{
_newW = t;
_newH = (t / (double)_sourceImg.Width) * (double)_sourceImg.Height;
}
System.Drawing.Image bitmap = new System.Drawing.Bitmap((int)_newW, (int)_newH);
Graphics g = Graphics.FromImage(bitmap);

//获取或设置与此 Graphics 关联的插补模式。
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置图片的质量  高清质量获取或设置绘制到此 Graphics 的合成图像的呈现质量。
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(_sourceImg, new Rectangle(0, 0, (int)_newW, (int)_newH), new Rectangle(0, 0, _sourceImg.Width, _sourceImg.Height), //

GraphicsUnit.Pixel);// GraphicsUnit。Pixel 是一个枚举 将设备像素指定为度量单位。
_sourceImg.Dispose();
g.Dispose();
try
{
bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch
{
}

bitmap.Dispose();
}

}
}

 

posted @ 2014-04-11 16:30  小菜鸟飞飞  阅读(160)  评论(0编辑  收藏  举报