ASP.NET 使用FileUpload控件上传图片并自动生成缩略图

来源:互联网 发布:单片机通讯光耦隔离 编辑:程序博客网 时间:2024/06/06 00:36

string fileExtension = System.IO.Path.GetExtension(img_path.FileName).ToLower();
        string path_to, path1_to;
        Bitmap bmp1;
        FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath("/" + img_path.FileName));


        path_to = "/" + DateTime.Now.ToShortDateString() + "-" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + fileExtension;
        path1_to = "/222" + DateTime.Now.ToShortDateString() + "-" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + fileExtension;

        img_path.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(path_to));
        bmp1 = new Bitmap(HttpContext.Current.Server.MapPath(path_to));
        Bitmap bmp2;

        int iwidth=160, iheight=120, thiswidth, thisheight;
        thiswidth = Convert.ToInt32(bmp1.Width);
        thisheight = Convert.ToInt32(bmp1.Height);
        if (thiswidth > thisheight)
        {
            //if (thiswidth >= 160)
            //{
            //    iwidth = 160;
            //}
            //else
            //{
            //    iwidth = thiswidth;
            //}
            iwidth = thiswidth >= 160 ? 160 : thiswidth;
            iheight = (iwidth * thisheight) / thiswidth;

            if (iheight > 120)
            {
                iwidth = (120 * iwidth) / iheight;
                iheight = 120;

            }
        }
        if (thiswidth < thisheight)
        {
            //if (thisheight > 120)
            //{
            //    iheight = 120;
            //}
            //else
            //{
            //    iheight = thisheight;
            //}
            iheight = thisheight >= 120 ? 120 : thisheight;
            iwidth = (iheight * thiswidth) / thisheight;
            if (iwidth > 160)
            {
                iheight = (160 * iheight) / iwidth;
                iwidth = 160;
            }
        }
        if (thisheight == thiswidth)
        {
            iwidth = iheight = thisheight > 120 ? 120 : thisheight;
        }
        bmp2 = new Bitmap(bmp1, iwidth, iheight);
       
        bmp2.Save(HttpContext.Current.Server.MapPath(path1_to));
        bmp1.Clone();
        bmp2.Clone();
        Label2.Text = "thiswidth:" + thiswidth + "   thisheight:" + thisheight + "    iwidth:" + iwidth + "   iheight:" + iheight;