|
在ASP.NET中可以轻松的实现图片的缩略图功能
/// <summary> /// 生成缩略图 /// 参数:ImagePath,width,height /// </summary> private string NewMiniImgge(string ImagePath, int Width, int Height) { System.Drawing.Image OldImage = System.Drawing.Image.FromFile(Server.MapPath(ImagePath)); double _W, _H; _W = Convert.ToDouble(Width); _H = Convert.ToDouble(Height); //检测原图大小 bool SL = false; //使用缩略模式 if (OldImage.Width > Width || OldImage.Height > Height) {
_W = Width; _H = OldImage.Height * Width / OldImage.Width; if (Convert.ToInt32(_H) > Height) {//宽度超过指定大小 _H = Height; _W = OldImage.Width * Height / OldImage.Height; } Response.Write(_W + "/" + _H); SL = true; }
//准备缩略图 if (SL == true) { //构造存储路径 string MiniImagePath = SavePath + "/Mini"; string ImageName = NewFileName(ImagePath); CheCkPath(Server.MapPath(MiniImagePath)); MiniImagePath += "/" + ImageName; Bitmap NewImage = new Bitmap(OldImage, Convert.ToInt32(_W), Convert.ToInt32(_H)); NewImage.Save(Server.MapPath(MiniImagePath)); NewImage.Dispose(); OldImage.Dispose(); return SavePath + "/Mini/" + ImageName; } else return ImagePath; }
其中使用了一个时间+随机数函数:NewFileName(FileName),其函数功能是根据文件的扩展名称重新生成一个新的文件名称。 另外有个函数就是CheCkPath(Path),该函数用来检查文件的存储路径是否存在,如果不存在则创建,代码如下:
/// <summary> ///检查文件路径,没有则创建 /// </summary> private void CheCkPath(string Path) { if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } }
要想使用以上所有功能,请在头部增加以下引用:
using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; /// <summary> /// 程序名称:文件上传模块 /// 程序作者:[?no恋人] /// 程序文件:UpLoad.aspx.cs /// 程序功能:本程序是用来实现文件功能的 /// 使用方法:直接使用 /// 版权声明:FREE-SHI保留所有权利,但是您可以任意引用\拷贝\传播本程序,但请保留本程序的完整及声明 /// 注意事项:"[?no恋人],[FREE-SHI]"为www.hfdxs.com网站所有人丁敬节的昵称和网名 /// /// </summary> |