using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Net;
using System.Drawing.Drawing2D;

namespace KstCmsBase.Common
{
    public class FStream
    {
        private int _FileSize;
        private string[] _FileType;




        public int FileSize { get { return _FileSize; } }

        public FStream()
        {
        }

        public FStream(int Size, params string[] FileType)
        {
            _FileSize = Size;
            _FileType = FileType;
        }
        /// <summary>
        /// 文件上传字节流
        /// </summary>
        /// <param name="FileUpload"></param>
        /// <returns>返回字节流</returns>
        public byte[] UploadFileToByte(FileUpload FileUpload)
        {
            byte[] FileByte = null;
            HttpPostedFile UpFile = FileUpload.PostedFile;
            int UpFileLenght = UpFile.ContentLength;
            if (UpFileLenght == 0)
            {
                throw new Exception("未选择上传的文件或文件无效！");
            }
            else if (UpFileLenght > _FileSize)
            {
                float FileSize = _FileSize / 1024;
                throw new Exception("上传的文件太大，请上传不要大于" + string.Format("{0:n}", FileSize) + " K的文件！");
            }
            string FileExt = UpFile.FileName.Substring(UpFile.FileName.LastIndexOf("."));
            Boolean T = false;
            for (int i = 0; i < _FileType.Length; i++)
            {
                if (FileExt.ToLower() == _FileType[i].ToString().ToLower())
                {
                    T = true;
                    break;
                }
            }

            if (!T)
            {
                throw new Exception("上传的文件类型错误!");

            }
            FileByte = new byte[UpFileLenght];
            System.IO.Stream FileStream = UpFile.InputStream;
            FileStream.Read(FileByte, 0, UpFileLenght);
            _FileSize = UpFileLenght;
            return FileByte;

        }


        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="FileUpload">文件域</param>
        /// <param name="UploadPath">上传路径,路径后要加上"/"</param>
        /// <returns>返回文件上传后的路径及文件名称</returns>
        public string UploadFile(System.Web.UI.WebControls.FileUpload FileUpload, string UploadPath)
        {

            string FilePath = null;
            HttpPostedFile UpFile = FileUpload.PostedFile;
            int UpFileLenght = UpFile.ContentLength;
          
            if (UpFileLenght == 0)
            {
                throw new Exception("未选择上传的文件或文件无效！");
            }
            else if (UpFileLenght > _FileSize)
            {
                float FileSize = _FileSize / 1024;
                throw new Exception("上传的文件太大，请上传不要大于" + string.Format("{0:n}",FileSize) + " K的文件！");
            }
            string FileExt = UpFile.FileName.Substring(UpFile.FileName.LastIndexOf("."));
            Boolean T = false;
            for (int i = 0; i < _FileType.Length; i++)
            {
                if (FileExt.ToLower() == _FileType[i].ToString().ToLower())
                {
                    T = true;
                    break;
                }
            }

            if (!T)
            {
                throw new Exception("上传的文件类型错误!");

            }
            string FileName = System.IO.Path.GetFileName(UpFile.FileName);
            try
            {
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(UploadPath)))
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(UploadPath));
                UpFile.SaveAs(HttpContext.Current.Server.MapPath(UploadPath) + FileName);
                FilePath = UploadPath + FileName;

            }
            catch (Exception er)
            {
                throw new Exception(er.Message);

            }

            return FilePath;

        }

        /// <summary>
        /// 处理成缩略图
        /// </summary>
        /// <param name="PicUrl">原图</param>
        /// <param name="TargetPath">处理后的缩略图保存路么,记得以/结尾</param>
        /// <param name="img_w"></param>
        /// <param name="img_h"></param>
        /// <returns></returns>
        public string Set_SmallImg(string PicUrl, string TargetPath, int img_w, int img_h)
        {

            MemoryStream ms = new MemoryStream(getFilebyte(PicUrl));
            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(ms);
            
            int x, y, w, h;
            if (originalImage.Width > 160 && originalImage.Height > 120)
            {
                w = img_w;
                h = img_w * originalImage.Height / originalImage.Width;
                if (h > img_h)
                {
                    h = img_h;
                    w = img_h * originalImage.Width / originalImage.Height;
                    x = (img_w - w) / 2;
                    y = 0;
                }
                else
                {
                    x = 0;
                    y = (img_h - h) / 2;
                }
            }
            else if (originalImage.Width > img_w)
            {
                w = img_w;
                h = img_w * originalImage.Height / originalImage.Width;
                x = 0;
                y = (img_h - h) / 2;
            }
            else if (originalImage.Height > img_h)
            {
                h = img_h;
                w = img_h * originalImage.Width / originalImage.Height;
                x = (img_w - w) / 2;
                y = 0;
            }
            else
            {
                w = originalImage.Width;
                h = originalImage.Height;
                x = (img_w - w) / 2;
                y = (img_h - h) / 2;
            }
            Bitmap bm = new Bitmap(img_w, img_h);
            Graphics g = Graphics.FromImage(bm);

            // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
            //g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // 指定高质量、低速度呈现。
            //g.SmoothingMode = SmoothingMode.HighQuality;

            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.Clear(Color.White);
            g.DrawImage(originalImage, new Rectangle(x, y, w, h), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel);

            long[] quality = new long[1];
            quality[0] = 100;

            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo jpegICI = null;
            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[i];//设置JPEG编码
                    break;
                }
            }
            if (jpegICI != null)
            {
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(TargetPath)))
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(TargetPath));
                TargetPath += Fucs.Rnd() + ".jpg";

                bm.Save(HttpContext.Current.Server.MapPath(TargetPath), jpegICI, encoderParams);
            }
            else
            {
                TargetPath = PicUrl;
            }

            bm.Dispose();
            originalImage.Dispose();
            g.Dispose();
            return TargetPath;

        }

        private  byte[] getFilebyte(string vFilePath)
        {
            byte[] Result;
            try
            {
                Result = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(vFilePath));

            }
            catch
            {
                Result = null;
            }
            return Result;
        }
    }
}
