<%@ WebHandler Language="c#" Class="UploadAvatar" Debug="true" %>
using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using Dcx.Config;
using Dcx.Common;
using Dcx.BLL;
 
public class UploadAvatar : IHttpHandler, System.Web.SessionState.IRequiresSessionState  //实现这个接口，意味着要实现该接口的两个方法： ProcessRequest和 IsReusable
{
 

    [System.Web.Services.WebMethod(EnableSession = true)]
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Charset = "utf-8";
        if (context.Request.Files.Count > 0)
        {
            string errMsg = "";
            int successCount = 0;
            int userId=Dcx .Common .VonleHelper .GetUserId_FromSession ();
            if (!Dcx.Common.VonleHelper.IsLogined())
            {
                context.Response.Write("0");  //返回最后结果
                context.Response.End();
                return;
            }
   
             //Dcx.BLL. Avatars. GetAvatarUrl( uid, AvatarSize avatarSize)
            
            bool IsOk =SaveRequestAvatarFile( context,  5*1024);// Dcx.Common.FileOperate.UpLoadFile(context, false, ref  successCount, ref  errMsg);
            //返回最后结果
            if (IsOk)
                context.Response.Write("ChangeIsOk");
            else
                context.Response.Write("ChangeIsFail");  //返回最后结果
            context.Response.End();
        }
     

    }
    ///// <summary>
    ///// 获取头像地址
    ///// </summary>
    ///// <param name="uid">用户Id</param>
    ///// <param name="avatarSize">头像大小，1：大，2：中，3：小</param>
    ///// <returns></returns>
    //public static string GetAvatarUrl(string uid, AvatarSize avatarSize)
    //{
    //    uid = FormatUid(uid);
    //    string size = "";
    //    switch (avatarSize)
    //    {
    //        case AvatarSize.Large:
    //            size = "large";
    //            break;
    //        case AvatarSize.Medium:
    //            size = "medium";
    //            break;
    //        case AvatarSize.Small:
    //            size = "small";
    //            break;
    //    }
    //    string physicsAvatarPath = string.Format(AVATAR_URL, uid.Substring(0, 3), uid.Substring(3, 2), uid.Substring(5, 2), uid.Substring(7, 2), size);
    //    return physicsAvatarPath;// Utils.GetRootUrl(forumPath) + "avatars/" +
    //}


    /// <summary>保存上传头像
    /// </summary>
    /// <param name="MaxAllowFileSize">最大允许的头像文件尺寸(单位:KB)</param>
    /// <returns>保存文件的相对路径</returns>
    public static bool  SaveRequestAvatarFile(HttpContext context, int MaxAllowFileSize)
    {
        if (context.Request.Files == null || context.Request.Files.Count <1)
            return false ;
        HttpPostedFile postedFile = context.Request.Files[0];   //得到上传文件的对象
        string filename = Path.GetFileName(postedFile.FileName);
        string fileextname = Path.GetExtension(filename).ToLower();
        string filetype = postedFile.ContentType.ToLower();
        string AVATAR_URL = "/UploadFiles/head/{0}/{1}/{2}/";//{3}_avatar_{4}.
        string uid = Dcx.Common.VonleHelper.GetUserId_FromSession().ToString();
        uid = Dcx.BLL.Avatars.FormatUid(uid);
        string[] fileType ={ "large", "medium", "small" };
        int[] sizeType ={ 150, 50, 30 };
        string size = "";
        //switch (avatarSize)
        //{
        //    case Dcx.BLL.AvatarSize.Large:
        //        size = "large";
        //        break;
        //    case AvatarSize.Medium:
        //        size = "medium";
        //        break;
        //    case AvatarSize.Small:
        //        size = "small";
        //        break;
        //}
        string savePath = string.Format(AVATAR_URL, uid.Substring(0, 3), uid.Substring(3, 2), uid.Substring(5, 2));//, uid.Substring(7, 2), size

        // 判断 文件扩展名/文件大小/文件类型 是否符合要求
        if (Utils.InArray(fileextname, ".jpg,.gif,.png") && filetype.StartsWith("image"))
        {
            //StringBuilder savedir = new System.Text.StringBuilder("/UploadFiles/head/");//Dcx.Config.BaseConfigs.GetSystemPath +

            //int t1 = (int)((double)userid / (double)10000);
            //savedir.Append(t1);
            //savedir.Append("/");
            //int t2 = (int)((double)userid / (double)200);
            //savedir.Append(t2);
            //savedir.Append("/");

            int pPartStartPointX = 0;
            if (context.Request.Form["x1"] != null && context.Request.Form["x1"].ToString() != "" && Dcx.Common.Validator.IsValidInt2(context.Request.Form["x1"].ToString()))
                pPartStartPointX = Dcx.Common.TypeConverter.StrToInt(context.Request.Form["x1"].ToString());

            int pPartStartPointY = 0;
            if (context.Request.Form["y1"] != null && context.Request.Form["y1"].ToString() != "" && Dcx.Common.Validator.IsValidInt2(context.Request.Form["y1"].ToString()))
                pPartStartPointY = Dcx.Common.TypeConverter.StrToInt(context.Request.Form["y1"].ToString());

            int pPartWidth = 0;
            if (context.Request.Form["w"] != null && context.Request.Form["w"].ToString() != "" && Dcx.Common.Validator.IsValidInt2(context.Request.Form["w"].ToString()))
                pPartWidth = Dcx.Common.TypeConverter.StrToInt(context.Request.Form["w"].ToString());

            int pPartHeight = 0;
            if (context.Request.Form["h"] != null && context.Request.Form["h"].ToString() != "" && Dcx.Common.Validator.IsValidInt2(context.Request.Form["h"].ToString()))
                pPartHeight = Dcx.Common.TypeConverter.StrToInt(context.Request.Form["h"].ToString());

            int pOrigStartPointX = 0;
            //if(context.Request.Form ["x1"]!=null &&context.Request.Form ["x1"].ToString ()!=""&& Dcx .Common .Validator .IsValidInt2  (context.Request.Form ["x1"].ToString ()))
            //  pOrigStartPointX=  Dcx .Common .TypeConverter .StrToInt (context.Request.Form ["x1"].ToString ());

            int pOrigStartPointY = 0;
            //if(context.Request.Form ["x1"]!=null &&context.Request.Form ["x1"].ToString ()!=""&& Dcx .Common .Validator .IsValidInt2  (context.Request.Form ["x1"].ToString ()))
            //  pOrigStartPointY=  Dcx .Common .TypeConverter .StrToInt (context.Request.Form ["x1"].ToString ());

            int sourceWidth = 0;
            if (context.Request.Form["sw"] != null && context.Request.Form["sw"].ToString() != "" && Dcx.Common.Validator.IsValidInt2(context.Request.Form["sw"].ToString()))
                sourceWidth = Dcx.Common.TypeConverter.StrToInt(context.Request.Form["sw"].ToString());
            int sourceHeight = 0;
            if (context.Request.Form["sh"] != null && context.Request.Form["sh"].ToString() != "" && Dcx.Common.Validator.IsValidInt2(context.Request.Form["sh"].ToString()))
                sourceHeight = Dcx.Common.TypeConverter.StrToInt(context.Request.Form["sh"].ToString());

            int imageWidth = 0;
            //if (context.Request.Form["x1"] != null && context.Request.Form["x1"].ToString() != "" && Dcx.Common.Validator.IsValidInt2(context.Request.Form["x1"].ToString()))
            //    imageWidth = Dcx.Common.TypeConverter.StrToInt(context.Request.Form["x1"].ToString());

            int imageHeight = 0;
            //if (context.Request.Form["x1"] != null && context.Request.Form["x1"].ToString() != "" && Dcx.Common.Validator.IsValidInt2(context.Request.Form["x1"].ToString()))
            //    imageHeight = Dcx.Common.TypeConverter.StrToInt(context.Request.Form["x1"].ToString());




            //SaveCutPic(postedFile.FileName, savePath, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight, pOrigStartPointX, pOrigStartPointY, 180, 180);

            //SaveCutPic(postedFile.FileName, savePath, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight, pOrigStartPointX, pOrigStartPointY, 50, 50);
            if (!Directory.Exists(Dcx.Common.Utils.GetMapPath(savePath.ToString())))
                Utils.CreateDir(Dcx.Common.Utils.GetMapPath(savePath.ToString()));
            savePath = context.Server.MapPath(savePath);
            savePath = savePath + uid.Substring(7, 2) + "_avatar_";

            using (Image originalImg = Image.FromStream(postedFile.InputStream ))// .FromFile(postedFile.FileName))
            {
                Bitmap thumimg = MakeThumbnail(originalImg, sourceWidth, sourceHeight);
                //剪切图
                Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);
                
                #region 生成先缩略，再剪切后的图片 partImg
                Graphics graphics = Graphics.FromImage(partImg);
                //目标位置 
                Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));
                //原图位置（默认从原图中截取的图片大小等于目标图片的大小） 
                Rectangle origRect = new Rectangle(new Point(0, 0), new Size(pPartWidth, pPartHeight));
                ///文字水印   
                Graphics G = Graphics.FromImage(partImg);
                G.Clear(Color.White);
                // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。  
                G.InterpolationMode = InterpolationMode.HighQualityBicubic;
                // 指定高质量、低速度呈现。  
                G.SmoothingMode = SmoothingMode.HighQuality;
                graphics.DrawImage(thumimg, origRect , destRect, GraphicsUnit.Pixel);
                #endregion
                G.Dispose();

                originalImg.Dispose();

                ////创建一个bitmap类型的bmp变量来读取文件。
                //Bitmap bmp = new Bitmap(openFileDialog1.FileName);
                ////新建第二个bitmap类型的bmp2变量，我这里是根据我的程序需要设置的。
                //Bitmap bmp2 = new Bitmap(1024, 768, PixelFormat.Format16bppRgb555);
                ////将第一个bmp拷贝到bmp2中
                //Graphics draw = Graphics.FromImage(bmp2);
                //draw.DrawImage(bmp, 0, 0);
                //pictureBox1.Image = (Image)bmp2;//读取bmp2到picturebox
                //FILE = openFileDialog1.FileName;
                //openFileDialog1.Dispose();
                //draw.Dispose();
                //bmp.Dispose();//释放bmp文件资源
                
                //生成三个缩略图，并保存
                for (int i = 0; i < fileType.Length; i++)// fileType.Length
                {
                    size = fileType.GetValue(i).ToString();
                    //string filePath = savePath + uid.Substring(7, 2) + "_avatar_" + size + ".png";
                    string filePath = savePath + size + ".jpg";
                    //string filePath = pSavedPath + "\\" + filename;
                    //生成缩略图
                    int w = Dcx.Common.TypeConverter.ObjectToInt(sizeType.GetValue(i));
                    Bitmap thumimg2 = MakeThumbnail(partImg, w, w);

                    if (File.Exists(filePath))
                    {
                        File.SetAttributes(filePath, FileAttributes.Normal);
                        File.Delete(filePath);
                    }
                    thumimg2.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    thumimg2.Dispose();

                }
                //释放
                //G.Dispose();
                partImg.Dispose();
                thumimg.Dispose();
                //originalImg.Dispose();

            }
            return true;
        }

        //string newfilename = savedir.ToString() + userid.ToString() + fileextname;

        //if (HttpContext.Current.Request.Files[0].ContentLength <= MaxAllowFileSize)
        //{
        //    File.Delete(Utils.GetMapPath(savedir.ToString()) + userid.ToString() + ".jpg");
        //    File.Delete(Utils.GetMapPath(savedir.ToString()) + userid.ToString() + ".gif");
        //    File.Delete(Utils.GetMapPath(savedir.ToString()) + userid.ToString() + ".png");

        //    HttpContext.Current.Request.Files[0].SaveAs(Utils.GetMapPath(newfilename));
        //    return newfilename;
        //}
        return true ;
    }
 

    
    /// <summary>保存上传头像，在缩略图的基础上剪切
    /// </summary>
    public static string SaveCutPic(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight)
    {
        using (Image originalImg = Image.FromFile(pPath))
        {
            if (originalImg.Width == imageWidth && originalImg.Height == imageHeight)
            {
                return SaveCutPic(pPath, pSavedPath, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight,
                        pOrigStartPointX, pOrigStartPointY);

            }
            string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
            string filePath = pSavedPath + "\\" + filename;

            //生成缩略图
            Bitmap thumimg = MakeThumbnail(originalImg, imageWidth, imageHeight);

            //剪切图
            Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);

            Graphics graphics = Graphics.FromImage(partImg);
            Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置 
            Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置（默认从原图中截取的图片大小等于目标图片的大小） 

            ///文字水印   
            Graphics G = Graphics.FromImage(partImg);
            //Font f = new Font("Lucida Grande", 6); 
            //Brush b = new SolidBrush(Color.Gray); 
            G.Clear(Color.White);
            // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。  
            G.InterpolationMode = InterpolationMode.HighQualityBicubic;
            // 指定高质量、低速度呈现。  
            G.SmoothingMode = SmoothingMode.HighQuality;

            graphics.DrawImage(thumimg, destRect, origRect, GraphicsUnit.Pixel);
            //G.DrawString("Xuanye", f, b, 0, 0); 
            G.Dispose();

            originalImg.Dispose();
            if (File.Exists(filePath))
            {
                File.SetAttributes(filePath, FileAttributes.Normal);
                File.Delete(filePath);
            }
            partImg.Save(filePath, ImageFormat.Jpeg);

            partImg.Dispose();
            thumimg.Dispose();
            return filename;
        }
    }

    /// <summary>生成缩略图
    /// </summary>
    public static Bitmap MakeThumbnail(Image fromImg, int width, int height)
    {
        Bitmap bmp = new Bitmap(width, height);
        int ow = fromImg.Width;
        int oh = fromImg.Height;

        //新建一个画板 
        Graphics g = Graphics.FromImage(bmp);

        //设置高质量插值法 
        g.InterpolationMode = InterpolationMode.High;
        //设置高质量,低速度呈现平滑程度 
        g.SmoothingMode = SmoothingMode.HighQuality;
        //清空画布并以透明背景色填充 
        g.Clear(Color.Transparent);

        g.DrawImage(fromImg, new Rectangle(0, 0, width, height),
            new Rectangle(0, 0, ow, oh),
            GraphicsUnit.Pixel);

        return bmp;

    }

    /// <summary>保存上传头像，在原图上剪切
    /// </summary>
    public static string SaveCutPic(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY)
    {
        string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
        string filePath = pSavedPath + "\\" + filename;

        using (Image originalImg = Image.FromFile(pPath))
        {
            Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);
            Graphics graphics = Graphics.FromImage(partImg);
            Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置 
            Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置（默认从原图中截取的图片大小等于目标图片的大小） 

            //注释 文字水印   
            Graphics G = Graphics.FromImage(partImg);
            //Font f = new Font("Lucida Grande", 6); 
            //Brush b = new SolidBrush(Color.Gray); 
            G.Clear(Color.White);
            // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。  
            G.InterpolationMode = InterpolationMode.HighQualityBicubic;
            // 指定高质量、低速度呈现。  
            G.SmoothingMode = SmoothingMode.HighQuality;

            graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
            //G.DrawString("Xuanye", f, b, 0, 0); 
            G.Dispose();

            originalImg.Dispose();
            if (File.Exists(filePath))
            {
                File.SetAttributes(filePath, FileAttributes.Normal);
                File.Delete(filePath);
            }
            partImg.Save(filePath, ImageFormat.Jpeg);
            partImg.Dispose();
        }
        return filename;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


}
