ASP.NET(C#)生成缩略图

本文介绍了一种在C#中生成图片缩略图的方法。首先检查上传文件是否为图片格式,然后读取原始图片并获取其尺寸。接着按比例调整图片大小以创建缩略图,并使用高质量插值法及平滑模式进行绘制。最后将图片保存到指定路径。

必须先引用命名空间:

  using System.IO;

 

if (FileUpload1.PostedFile.ContentType.ToLower().IndexOf("image"< 0)
        
{
            FunctionUtility.JavaScriptHelper.Alert(
"上传图片格式不正确!");
            
return;
        }


        
//生成原图
        Byte[] oFileByte = new Byte[FileUpload1.PostedFile.ContentLength];
        Stream oStream 
= FileUpload1.PostedFile.InputStream;
        System.Drawing.Image oImage 
= System.Drawing.Image.FromStream(oStream);

        
//原图宽度和高度
        int oWidth = oImage.Width;
        
int oHeight = oImage.Height;

        
//设置缩略图的初始宽度和高度
        int tWidth = 200;
        
int tHeight = 200;

        
//按比例计算出缩略图的宽度和高度
        if (oWidth >= oHeight)
        
{
            tHeight 
= (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
        }

        
else
        
{
            tWidth 
= (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
        }


        
//生成缩略图
        Bitmap tImage = new Bitmap(tWidth, tHeight);
        Graphics g 
= Graphics.FromImage(tImage);

        
//指定高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        
//指定高质量低速度呈现
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        
//清空画布并以透明背景色填充
        g.Clear(Color.Transparent);

        g.DrawImage(oImage, 
new Rectangle(00, tWidth, tHeight), new Rectangle(00, oWidth, oHeight), GraphicsUnit.Pixel);

        
//设置文件名称
        string setFileName = FunctionUtility.FileHelper.GetDateTimeFileName()+".jpg";
        
//保存原图的物理路径
        string oFullName = Server.MapPath("/DesignImages/Images/YT/" + setFileName);
        
//保存缩略图物理路径
        string tFullName = Server.MapPath("/DesignImages/Images/SLT/" + setFileName);

        
//以JPG格式保存图片并释放占用的资源
        try
        
{
            oImage.Save(oFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
            tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);

            Image1.Visible 
= true;
            Image2.Visible 
= true;
            Image1.ImageUrl 
= "/DesignImages/Images/YT/" + setFileName;
            Image2.ImageUrl 
= "/DesignImages/Images/SLT/" + setFileName;

            FunctionUtility.JavaScriptHelper.Alert(
"缩略图生成成功!");
        }

       
catch (Exception oe)
        
{
            
throw oe;
        }

        
finally
        
{
            oImage.Dispose();
            g.Dispose();
            tImage.Dispose();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值