大图片自动生成缩略图

时间:2021-04-04 06:04:19

using System;
using System.Configuration;
using System.Data;
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.IO;
using System.Drawing;
using System.Collections;
using System.Drawing.Imaging;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }


    //// <summary>
    /// 按比例缩小图片,自动计算宽度
    /// </summary>
    /// <param name="strOldPic">源图文件名(包括路径)</param>
    /// <param name="strNewPic">缩小后保存为文件名(包括路径)</param>
    /// <param name="intHeight">缩小至高度</param>
    public void SmallPicWidth(string strOldPic, string strNewPic, int intHeight)
    {
        Bitmap objPic, objNewPic;
        try
        {
            objPic = new Bitmap(strOldPic);
            int intWidth = (intHeight / objPic.Height) * objPic.Width;
            objNewPic = new Bitmap(objPic, intWidth, intHeight);
            objNewPic.Save(strNewPic);
        }
        catch (Exception exp) { throw exp; }
        finally
        {
            objPic = null;
            objNewPic = null;
        }
    }
    /**/
    /// <summary>
    /// 缩小图片
    /// </summary>
    /// <param name="strOldPic">源图文件名(包括路径)</param>
    /// <param name="strNewPic">缩小后保存为文件名(包括路径)</param>
    /// <param name="intWidth">缩小至宽度</param>
    /// <param name="intHeight">缩小至高度</param>
    public void SmallPic(string strOldPic, string strNewPic, int intWidth, int intHeight)
    {
        Bitmap objPic, objNewPic;
        try
        {
            objPic = new Bitmap(strOldPic);
            objNewPic = new Bitmap(objPic, intWidth, intHeight);
            objNewPic.Save(strNewPic);
        }
        catch (Exception exp)
        { throw exp; }
        finally
        {
            objPic = null;
            objNewPic = null;
        }
    }
    protected string NewImage()
    {
        string type = Path.GetExtension(this.FileUpload1.PostedFile.FileName).ToLower().Trim();
        Random r = new Random();

        string name = System.DateTime.Now.ToString("yyyyMMddhhmmssfff") + r.Next(0, 100) + type;
        string serverpath = Server.MapPath("~/UpLoadImag/") + name;
        this.FileUpload1.PostedFile.SaveAs(serverpath);

        return serverpath;
    }

 

 


           /**//// <summary>
        /// 图片上传,带上缩略图
    /// </summary>
        /// <param name="FileUpload1">上传的控件的ID</param>
        /// <param name="SavePath">保存的路径,相对路径如“/Images/Picture/”,使用配置文件</param>
        /// <param name="refName">返回的文件名,不带路径</param>
        /// <param name="width">缩略图的宽</param>
        /// <param name="height">缩略图的高</param>
        /// <param name="maxLength">图片最大的大小</param>
        /// <returns></returns>
        public  bool UpLoadImage(FileUpload FileUpload1, string SavePath, string refName, int width, int height, int maxLength)
        {
            //在转换的时候需求使用系统路径
            SavePath = "~" + SavePath;
            /**////成功状态
            bool ret = true;
            /**////上传文件名称组
            string fileNames = string.Empty;
            //上传文件总大小
            int fileLength = 0;
            //图片类型
            string imgType = string.Empty;
            //图片类型集合
            ICollection ic = new string[] { ".gif", ".jpg", ".GIF", ".JPG" };
            ArrayList imgTypes = new ArrayList(ic);

            /**////判断上传文件的有效性

            ///检查文件扩展名字
            string name = System.IO.Path.GetFileName(FileUpload1.FileName);
            if (name == "")
            {
                /**////状态信息
                ret = false;
                refName = "图片不存在";
                return false;
            }
            imgType = System.IO.Path.GetExtension(FileUpload1.FileName);
            if (!imgTypes.Contains(imgType))
            {
                /**////状态信息
                ret = false;
                refName = "图片格式不对";
                return false;
            }
            fileLength = fileLength + FileUpload1.PostedFile.ContentLength;

            //系统规定大小
            int sysLength = maxLength * 1024;
            if (fileLength > sysLength)
            {
                /**////状态信息
                ret = false;
                refName = "图片超过200KB上限!";
                 return false;
            }
            /**////图片上传
            try
            {
                string picPath = SavePath;

                string fileName, fileExtension;
                /**////上传文件的文件名
                fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
                if (fileName != "")
                {
                    /**////上传文件的扩展名
                    fileExtension = System.IO.Path.GetExtension(fileName);
                    /**////生成新的文件名
                    fileName = DateTime.Now.ToString("yyyyMMddHHmmffff") + fileExtension;
                    /**////可根据扩展名字的不同保存到不同的文件夹
                    string date = DateTime.Now.ToString("yyyyMM");
                    picPath = Server.MapPath(picPath + date + "/");
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(picPath);
                    if (!di.Exists)
                    {
                        di.Create();
                    }
                    /**////注意:可能要修改您的文件夹的匿名写入权限。
                    FileUpload1.PostedFile.SaveAs(picPath + fileName);
                    refName = date + "/" + fileName;
                    GetThumbnailImage(SavePath , date + "/", fileName, width, height);
                }

            }
            catch
            {

                ret = false;
                refName = "上传失败!";
                return false;
            }
            return ret;
        }
 

 //生成缩略图代码:

 

/**//// <param name="SavePath">原始路径</param>
        /// <param name="pathDate">添加的月份路径</param>
        /// <param name="picFilePath">保存的文件名</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        public void GetThumbnailImage(string SavePath, string pathDate,string picFilePath, int width, int height)
        {
            //添加small100的前缀大小
       //程序内相对的服务器路径小图片
      string strRelativeSmallPath = SavePath + pathDate;

            string SmallPath100 = Server.MapPath(strRelativeSmallPath + picFilePath);
            string machpath = Server.MapPath(SavePath + pathDate + picFilePath);
            string isDir = SmallPath100.Substring(0, SmallPath100.LastIndexOf('/'));
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(isDir);
            if (!di.Exists)
            {
                di.Create();
            }
            Bitmap img = new Bitmap(machpath);  //read picture to memory

            int h = img.Height;
            int w = img.Width;
            int ss, os;// source side and objective side
            double temp1, temp2;
            //compute the picture's proportion
            temp1 = (h * 1.0D) / height;
            temp2 = (w * 1.0D) / width;
            if (temp1 < temp2)
            {
                ss = w;
                os = width;
            }
            else
            {
                ss = h;
                os = height;
            }

            double per = (os * 1.0D) / ss;
            if (per < 1.0D)
            {
                h = (int)(h * per);
                w = (int)(w * per);
            }
            // create the thumbnail image
          System.Drawing.Image imag2 =null;
              //img.GetThumbnailImage(w, h,
            //     new System.Drawing.Image.GetThumbnailImageAbort(10, IntPtr.Zero));
            Bitmap tempBitmap = new Bitmap(w, h);
            System.Drawing.Image tempImg = System.Drawing.Image.FromHbitmap(tempBitmap.GetHbitmap());
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(tempImg);
            g.Clear(Color.White);

            int x, y;

            x = (tempImg.Width - imag2.Width) / 2;
            y = (tempImg.Height - imag2.Height) / 2;

            g.DrawImage(imag2, x, y, imag2.Width, imag2.Height);

            try
            {
                if (img != null)
                    img.Dispose();
                if (imag2 != null)
                    imag2.Dispose();
                if (tempBitmap != null)
                    tempBitmap.Dispose();

                string fileExtension = System.IO.Path.GetExtension(machpath).ToLower();
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题. 
                switch (fileExtension)
                {
                    case ".gif": tempImg.Save(SmallPath100, ImageFormat.Gif); break;
                    case ".jpg": tempImg.Save(SmallPath100, ImageFormat.Jpeg); break;
                    case ".bmp": tempImg.Save(SmallPath100, ImageFormat.Bmp); break;
                    case ".png": tempImg.Save(SmallPath100, ImageFormat.Png); break;
                }                               
            }
            catch
            {
                throw new Exception("图片上传失败");
            }
            finally
            {
                //释放内存
                if (tempImg != null)
                    tempImg.Dispose();
                if (g != null)
                    g.Dispose();
            }
        }


    protected void Button1_Click(object sender, EventArgs e)
    {
        string name1 = NewImage();
        //string type = Path.GetExtension(this.FileUpload1.PostedFile.FileName).ToLower().Trim();
        string name2 = Server.MapPath("~/UpLoadImage/")+"2.jpg";

        //UpLoadImage(FileUpload1, "uploadimag", "", 300, 300, 3000);
        SmallPic( name1,name2, 300, 300);
    }
}