using Blur;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
//using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
namespace Helper
{
    public static class ImageHelper
    {
        /// <summary>
        /// 加载图片
        /// </summary>
        [ComVisible(true)]
        public static Image GetImage(string url)
        {
            try
            {
                if (CommonHelper.IsBase64String(url))
                {
                    return ConvertEx.Base64ToObject(url) as Image;
                }
                if (url.Contains("http"))
                {
                    HttpHelper.SetSSL();
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Accept = "text/html, application/xhtml+xml, */*";
                    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
                    req.ProtocolVersion = HttpVersion.Version11;
                    ServicePointManager.Expect100Continue = false;
                    req.Timeout = HttpHelper.TimeOut == 0 ? 5000 : HttpHelper.TimeOut;
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)req.GetResponse();
                    return Image.FromStream(myHttpWebResponse.GetResponseStream());
                }
                else { return Image.FromFile(url); }
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 搜索图片
        /// </summary>
        /// <param name="word">关键字</param>
        /// <param name="w">宽度</param>
        /// <param name="h">高度</param>
        /// <returns></returns>
        public static Image SearchImage(string word, int w, int h)
        {
            try
            {
                Random rd = new Random();
                string src = HttpHelper.Get(string.Format("https://pic.sogou.com/pics?query={0}&dm=4&cheight={1}&cwidth={2}&did={3}&mode=1&start=0&reqType=ajax&tn=0&reqFrom=detail", word, h, w, rd.Next(1, 5)));
                return GetImage(CommonHelper.GetMiddleText(src, "pic_url\":\"", "\",\"similarUrlFirst"));
            }
            catch (Exception)
            {
                return null;
            }
        }
        public static Image GaussianBlur(Image img, int r)
        {
            Blur.GaussianBlur br = new GaussianBlur(r);
            return br.ProcessImage(img);
        }
        public static System.Drawing.Image ResizeImage(System.Drawing.Image imgToResize, Size size)
        {
            System.Drawing.Image imgSource = imgToResize;
            System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;
            int sW = 0, sH = 0;
            // 按比例缩放           
            int sWidth = imgSource.Width;
            int sHeight = imgSource.Height;
            if (sHeight > size.Height || sWidth > size.Width)
            {
                if ((sWidth * size.Height) > (sHeight * size.Width))
                {
                    sW = size.Width;
                    sH = (size.Width * sHeight) / sWidth;
                }
                else
                {
                    sH = size.Height;
                    sW = (sWidth * size.Height) / sHeight;
                }
            }
            else
            {
                sW = sWidth;
                sH = sHeight;
            }
            Bitmap outBmp = new Bitmap(size.Width, size.Height);
            Graphics g = Graphics.FromImage(outBmp);
            g.Clear(Color.Transparent);
            // 设置画布的描绘质量         
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(imgSource, new Rectangle((size.Width - sW) / 2, (size.Height - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            // 以下代码为保存图片时，设置压缩质量     
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            imgSource.Dispose();
            return outBmp;
        }
        /// <summary>
        /// 转换Image为Icon
        /// </summary>
        /// <param name="image">要转换为图标的Image对象</param>
        /// <param name="nullTonull">当image为null时是否返回null。false则抛空引用异常</param>
        /// <exception cref="ArgumentNullException" />
        public static Icon ImageToIcon(Image image)
        {
            try
            {
                using (MemoryStream msImg = new MemoryStream()
                  , msIco = new MemoryStream())
                {
                    image.Save(msImg, ImageFormat.Png);
                    using (var bin = new BinaryWriter(msIco))
                    {
                        //写图标头部
                        bin.Write((short)0);           //0-1保留
                        bin.Write((short)1);           //2-3文件类型。1=图标, 2=光标
                        bin.Write((short)1);           //4-5图像数量（图标可以包含多个图像）
                        bin.Write((byte)image.Width);  //6图标宽度
                        bin.Write((byte)image.Height); //7图标高度
                        bin.Write((byte)0);            //8颜色数（若像素位深>=8，填0。这是显然的，达到8bpp的颜色数最少是256，byte不够表示）
                        bin.Write((byte)0);            //9保留。必须为0
                        bin.Write((short)0);           //10-11调色板
                        bin.Write((short)32);          //12-13位深
                        bin.Write((int)msImg.Length);  //14-17位图数据大小
                        bin.Write(22);                 //18-21位图数据起始字节
                        //写图像数据
                        bin.Write(msImg.ToArray());
                        bin.Flush();
                        bin.Seek(0, SeekOrigin.Begin);
                        return new Icon(msIco);
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        public static Bitmap CutImage(this Image image, Rectangle rect)
        {
            Bitmap bitmap = new Bitmap(rect.Width, rect.Height);
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.DrawImage(image, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel);
                return bitmap;
            }
        }
    }
}
