ASP.NET [C#] 生成缩略图

在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> 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值