示例#1
0
 void SetBackground(string str)
 {
     if (panel.InvokeRequired)
     {
         delegateString a = new delegateString(SetBackground);
         panel.Invoke(a, str);
     }
     else
     {
         var image = new KalikoImage(str);
         image.ApplyFilter(new FastGaussianBlurFilter(30.0f));
         image = image.Scale(new FitScaling(1024, 1024));
         panel.BackgroundImage = image.GetAsBitmap();
     }
 }
示例#2
0
        private void AddWaterMarking(WaterMarkingPosition?position, string waterMarkingPath, KalikoImage imageThumb)
        {
            if (!position.HasValue || string.IsNullOrEmpty(waterMarkingPath))
            {
                return;
            }
            //需要打上水印
            var waterMarkingImgage = new KalikoImage(waterMarkingPath);

            var waterMarkingWidth  = (int)(imageThumb.Width / 4.8);
            var waterMarkingHeight = (int)(waterMarkingImgage.Height * waterMarkingWidth / waterMarkingImgage.Width);
            var waterScalingBase   = new FitScaling(waterMarkingWidth, waterMarkingHeight);
            var waterThumb         = waterMarkingImgage.Scale(waterScalingBase);

            //计算距离
            var       waterX    = 0;
            var       waterY    = 0;
            const int edgeWidth = 40;

            switch (position.Value)
            {
            case WaterMarkingPosition.Center:
                waterX = (imageThumb.Width - waterThumb.Width) / 2;
                waterY = (imageThumb.Height - waterThumb.Height) / 2;
                break;

            case WaterMarkingPosition.LeftBottom:
                waterX = edgeWidth;
                waterY = imageThumb.Height - waterThumb.Height - edgeWidth;
                break;

            case WaterMarkingPosition.LeftTop:
                waterX = edgeWidth;
                waterY = edgeWidth;
                break;

            case WaterMarkingPosition.RightBottom:
                waterX = imageThumb.Width - waterThumb.Width - edgeWidth;
                waterY = imageThumb.Height - waterThumb.Height - edgeWidth;
                break;

            case WaterMarkingPosition.RightTop:
                waterX = imageThumb.Width - waterThumb.Width - edgeWidth;
                waterY = edgeWidth;
                break;
            }
            imageThumb.BlitImage(waterThumb, waterX, waterY);
        }
示例#3
0
        // GET: Activite/Details/5
        public ActionResult Details(int id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Activite A;

            A = activiteService.GetById((int)id);
            if (A == null)
            {
                return(HttpNotFound());
            }
            ActiviteVM pvm = new ActiviteVM()
            {
                ActiviteID  = A.ActiviteID,
                Title       = A.Title,
                Description = A.Description,
                Affiche     = A.Affiche,
                Document    = A.Document,
                Theme       = A.Theme,
                Outils      = A.Outils,
                AgeMin      = A.AgeMin,
                AgeMax      = A.AgeMax,
                ClassSize   = A.ClassSize,
                Duration    = A.Duration,
                Professor   = A.Professor,
                Start       = A.Start,
                Location    = A.Location,
                //    nomuser = User.Identity.GetUserName(),
                UserId = "f43c21cf-f35a-4897-a9e3-343c00afe7b3"
            };
            var t = activiteService.GetMany();

            foreach (Activite Act in t)
            {
                var         path1 = Path.Combine(Server.MapPath("~/Content/Uploads"), Act.Affiche);
                KalikoImage image = new KalikoImage(path1);
                KalikoImage thumb = image.Scale(new CropScaling(90, 80));
                var         path2 = Path.Combine(Server.MapPath("~/Content/Uploads"), Act.Title + "latest.jpg");
                thumb.SaveJpg(path2, 99);
            }
            List <Activite> Courses = t.ToList();

            ViewData["Courses"] = Courses;
            return(View(pvm));
        }
示例#4
0
        public static bool GenerateAvatar(Image inputImage, string userName, string mimetype)
        {
            try
            {
                string DestinationPath = HttpContext.Current.Server.MapPath("~/Storage/Avatars");

                var originalImage = new KalikoImage(inputImage);

                originalImage.Scale(new PadScaling(MaxWidth, MaxHeight)).SaveJpg(DestinationPath + '\\' + userName + ".jpg", 90);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
示例#5
0
        // generate a thumbnail while removing transparency and preserving aspect ratio
        public static string GenerateThumbFromUrl(string sourceUrl)
        {
            var randomFileName = GenerateRandomFilename();

            var request = WebRequest.Create(sourceUrl);

            request.Timeout = 300;
            var response = request.GetResponse();

            var originalImage = new KalikoImage(response.GetResponseStream())
            {
                BackgroundColor = Color.Black
            };

            originalImage.Scale(new PadScaling(MaxWidth, MaxHeight)).SaveJpg(DestinationPath + '\\' + randomFileName + ".jpg", 90);

            return(randomFileName + ".jpg");
        }
        // GET: Formation
        public ActionResult Index(string searchString, int?i)
        {
            var Formations = new List <FormationVM>();

            foreach (Formation p in MyFormationService.SearchFormByName(searchString))
            {
                if (string.IsNullOrEmpty(p.Affiche))
                {
                    var         path  = Path.Combine(Server.MapPath("~/Content/Front/images/event/event_02.jpg"));
                    KalikoImage image = new KalikoImage(path);
                    KalikoImage thumb = image.Scale(new CropScaling(250, 250));
                    var         path2 = Path.Combine(Server.MapPath("~/Content/Uploads"), p.Title + "thumb.jpg");
                    thumb.SaveJpg(path2, 99);
                }
                else
                {
                    var         path  = Path.Combine(Server.MapPath("~/Content/Uploads"), p.Affiche);
                    KalikoImage image = new KalikoImage(path);
                    KalikoImage thumb = image.Scale(new CropScaling(250, 250));
                    var         path2 = Path.Combine(Server.MapPath("~/Content/Uploads"), p.Title + "thumb.jpg");
                    thumb.SaveJpg(path2, 99);
                }


                Formations.Add(new FormationVM()
                {
                    FormationID = p.FormationID,
                    Title       = p.Title,
                    Start       = p.Start,
                    End         = p.End,
                    Description = p.Description,
                    // Affiche = p.Affiche,
                    Affiche  = p.Title + "thumb.jpg",
                    NbrMax   = p.NbrMax,
                    Theme    = p.Theme,
                    Location = p.Location,
                    Price    = p.Price
                });
            }
            return(View(Formations.ToPagedList(i ?? 1, 3)));
        }
示例#7
0
        /// <summary>
        /// 缩略图的截图模式是:当原图宽高比按照缩略图时缩放
        /// </summary>
        /// <param name="originalImagePath"></param>
        /// <param name="thumbnailPath"></param>
        /// <param name="extName"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="scale">Crop:取中间部分;Fit:按比例缩放,自动调整尺寸;Pad:按比例缩放,保持尺寸,不足部分填白</param>
        /// <param name="position">水印位置</param>
        /// <param name="waterMarkingPath">水印图片路劲</param>
        public void MakeThumbnail(string originalImagePath, string thumbnailPath, string extName, int width, int height, ThumbnailMethod scale = ThumbnailMethod.Fit, WaterMarkingPosition?position = null, string waterMarkingPath = "")
        {
            if (!File.Exists(originalImagePath))
            {
                return;
            }
            var image = new KalikoImage(originalImagePath)
            {
                BackgroundColor = Color.White
            };
            var         format      = GetImageFormat(extName);
            ScalingBase scalingBase = null;

            switch (scale)
            {
            case ThumbnailMethod.Crop:
                scalingBase = new CropScaling(width, height);
                break;

            case ThumbnailMethod.Fit:
                scalingBase = new FitScaling(width, height);
                break;

            case ThumbnailMethod.Pad:
                scalingBase = new PadScaling(width, height);
                break;

            default:
                scalingBase = new CropScaling(width, height);
                break;
            }
            var imageThumb = image.Scale(scalingBase);

            AddWaterMarking(position, waterMarkingPath, imageThumb);
            imageThumb.SaveImage(thumbnailPath, format);
            image.Dispose();
            imageThumb.Dispose();
        }
示例#8
0
 public void CropAndResizeImage(string inPutFilePath, string outPutFilePath, string outPuthFileName, int width, int height, bool pngFormat = false)
 {
     try
     {
         var image = Image.FromFile(HttpContext.Current.Server.MapPath(string.Concat("~/", inPutFilePath)));
         //if (!width.HasValue)
         //{
         //	width = new int?(image.Width);
         //}
         //if (!height.HasValue)
         //{
         //	height = new int?(image.Height);
         //}
         var kalikoImage  = new KalikoImage(image);
         var kalikoImage1 = kalikoImage.Scale(new PadScaling(width, height, Color.Transparent));
         //KalikoImage kalikoImage1 = kalikoImage.Scale(new FitScaling(width.Value, height.Value));
         if (!Directory.Exists(HttpContext.Current.Server.MapPath(string.Concat("~/", outPutFilePath))))
         {
             Directory.CreateDirectory(HttpContext.Current.Server.MapPath(string.Concat("~/", outPutFilePath)));
         }
         var str = HttpContext.Current.Server.MapPath(string.Concat("~/", Path.Combine(outPutFilePath, outPuthFileName)));
         if (!pngFormat)
         {
             kalikoImage1.SaveJpg(str, 99);
         }
         else
         {
             kalikoImage1.SavePng(str);
         }
         kalikoImage1.Dispose();
         kalikoImage.Dispose();
     }
     catch (Exception exception)
     {
         throw new Exception(exception.Message);
     }
 }
示例#9
0
 public void CropAndResizeImage(string inPutFilePath, string outPutFilePath, string outPuthFileName, int?width = null, int?height = null, bool pngFormat = false)
 {
     try
     {
         Image image = Image.FromFile(HttpContext.Current.Server.MapPath(string.Concat("~/", inPutFilePath)));
         if (!width.HasValue)
         {
             width = new int?(image.Width);
         }
         if (!height.HasValue)
         {
             height = new int?(image.Height);
         }
         KalikoImage kalikoImage  = new KalikoImage(image);
         KalikoImage kalikoImage1 = kalikoImage.Scale(new FitScaling(width.Value, height.Value));
         if (!Directory.Exists(HttpContext.Current.Server.MapPath(string.Concat("~/", outPutFilePath))))
         {
             Directory.CreateDirectory(HttpContext.Current.Server.MapPath(string.Concat("~/", outPutFilePath)));
         }
         string str = HttpContext.Current.Server.MapPath(string.Concat("~/", Path.Combine(outPutFilePath, outPuthFileName)));
         if (!pngFormat)
         {
             kalikoImage1.SaveJpg(str, (long)99);
         }
         else
         {
             kalikoImage1.SavePng(str);
         }
         kalikoImage1.Dispose();
         kalikoImage.Dispose();
     }
     catch (Exception exception)
     {
         throw new Exception(exception.Message);
     }
 }
示例#10
0
        // store uploaded avatar
        public static async Task <bool> GenerateAvatar(Image inputImage, string userName, string mimetype)
        {
            try
            {
                // store avatar locally
                var originalImage = new KalikoImage(inputImage);
                originalImage.Scale(new PadScaling(MaxWidth, MaxHeight)).SaveJpg(DestinationPathAvatars + '\\' + userName + ".jpg", 90);
                if (!Settings.UseContentDeliveryNetwork)
                {
                    return(true);
                }

                // call upload to storage since CDN is enabled in config
                string tempAvatarLocation = DestinationPathAvatars + '\\' + userName + ".jpg";

                // the avatar file was not found at expected path, abort
                if (!FileSystemUtility.FileExists(tempAvatarLocation, DestinationPathAvatars))
                {
                    return(false);
                }
                else if (Settings.UseContentDeliveryNetwork)
                {
                    // upload to CDN
                    await CloudStorageUtility.UploadBlobToStorageAsync(tempAvatarLocation, "avatars");

                    // delete local file after uploading to CDN
                    File.Delete(tempAvatarLocation);
                }
                return(true);
            }
            catch (Exception ex)
            {
                EventLogger.Log(ex);
                return(false);
            }
        }
示例#11
0
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="height">高度</param>
        /// <param name="width"></param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <param name="type">压缩缩放类型</param>
        /// <returns></returns>
        public static bool MakeThumbnail(string sFile, string dfolder, string newfilename, int height, int width, ThumbnailMode type, int flag = 100)
        {
            try
            {
                KalikoImage image = new KalikoImage(sFile);
                image.BackgroundColor = Color.Aquamarine;
                //缩放后的宽度和高度
                int towidth  = width;
                int toheight = height;
                //
                int x  = 0;
                int y  = 0;
                int ow = image.Width;
                int oh = image.Height;
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dfolder);
                if (!di.Exists) // 如果不存在目录则创建
                {
                    di.Create();
                }
                string dFile = dfolder + "\\" + newfilename;
                switch (type)
                {
                case ThumbnailMode.HW:    //指定高宽缩放(可能变形)
                {
                    break;
                }

                case ThumbnailMode.W:    //指定宽,高按比例
                {
                    toheight = image.Height * width / image.Width;
                    break;
                }

                case ThumbnailMode.H:    //指定高,宽按比例
                {
                    towidth = image.Width * height / image.Height;
                    break;
                }

                case ThumbnailMode.Cut:    //指定高宽裁减(不变形)
                {
                    if ((double)image.Width / (double)image.Height > (double)towidth / (double)toheight)
                    {
                        oh = image.Height;
                        ow = image.Height * towidth / toheight;
                        y  = 0;
                        x  = (image.Width - ow) / 2;
                    }
                    else
                    {
                        ow = image.Width;
                        oh = image.Width * height / towidth;
                        x  = 0;
                        y  = (image.Height - oh) / 2;
                    }
                    break;
                }

                default:
                    break;
                }

                var img       = image.Scale(new FitScaling(towidth, toheight));
                var extension = System.IO.Path.GetExtension(sFile);
                switch (extension.ToLower())
                {
                case ".png":
                    img.SavePng(dFile);
                    break;

                case ".gif":
                    img.SaveGif(dFile);
                    break;

                case ".ico":
                    img.SaveImage(dFile, ImageFormat.Icon);
                    break;

                case ".bmp":
                    img.SaveBmp(dFile);
                    break;

                case ".jpg":
                    img.SaveJpg(dFile, flag);
                    break;

                default:
                    img.SaveBmp(dFile);
                    break;
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#12
0
            public uint Def_ReadFile(string filename, IntPtr buffer, uint BufferSize, ref uint NumberByteReadSuccess, long Offset, IntPtr info)
            {
                StringBuilder data  = new StringBuilder();
                VNode         Node  = new VNode(filename);
                string        query = "";

                byte[] file = null;

                Console.WriteLine("reading {0} {1} {2}", Node.isValid, Node.fileName, Node.curDir);
                if (Node.isValid && Node.param.TryGetValue("q", out query))
                {
                    #region This Is google Service
                    if (Node.fileName.StartsWith("google", StringComparison.CurrentCultureIgnoreCase))
                    {
                        Task <Google.Apis.Customsearch.v1.Data.Search> ret;
                        if (Node.param.ContainsKey("n"))
                        {
                            int    n    = 1;
                            string temp = "";
                            Node.param.TryGetValue("n", out temp);
                            int.TryParse(temp, out n);
                            ret = ServiceProvider.SearchGoogle(query, n);
                        }
                        else
                        {
                            ret = ServiceProvider.SearchGoogle(query, 1);
                        }
                        ret.Wait();
                        if (ret.Result.Items != null)
                        {
                            foreach (Google.Apis.Customsearch.v1.Data.Result s in ret.Result.Items)
                            {
                                data.AppendLine(s.Title);
                                data.AppendLine("----------------------------------------------------------------");
                                data.AppendLine(s.Snippet);
                                data.AppendLine(s.Link);
                                data.Append("\n");
                            }
                        }
                        Console.WriteLine(data.ToString());
                        file = System.Text.Encoding.ASCII.GetBytes(data.ToString());
                    }
                    #endregion
                }
                else if (Node.curDir == "ImagePass")
                {
                    if (!Node.fileExtention.EndsWith("inf", StringComparison.CurrentCultureIgnoreCase) && !Node.fileExtention.EndsWith("ini", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (imageFiles.Any(name => name.StartsWith(Node.fileName)))
                        {
                            Console.WriteLine("Direct Read");
                            KalikoImage image = new KalikoImage(filepath + @"\" + imageFiles.Where(d => d.StartsWith(Node.fileName)).ToList()[0]);
                            Console.WriteLine("HEHFKHLDSKHFLSDHLKFHKD *()&*&(&**&(" + image.ByteArray.Length);
                            string width = "", height = "", OP = "", x = "", y = "";
                            System.IO.MemoryStream ms = new System.IO.MemoryStream();

                            Node.param.TryGetValue("op", out OP);
                            if (OP == "s" && Node.param.TryGetValue("w", out width) && Node.param.TryGetValue("h", out width))
                            {
                                int w = 0, h = 0;
                                if (int.TryParse(width, out w) && int.TryParse(width, out h))
                                {
                                    image.Scale(new FitScaling(w, h)).SavePng(ms);
                                }
                            }
                            if (OP == "c" && Node.param.TryGetValue("w", out width) && Node.param.TryGetValue("h", out width) && Node.param.TryGetValue("x", out x) && Node.param.TryGetValue("y", out y))
                            {
                                int w = 0, h = 0, X, Y;

                                if (int.TryParse(width, out w) && int.TryParse(width, out h) && int.TryParse(x, out X) && int.TryParse(y, out Y))
                                {
                                    image.Crop(X, Y, w, h);
                                }
                                image.SavePng(ms);
                            }

                            string ext = Node.fileExtention.ToLowerInvariant();


                            switch (ext)
                            {
                            case "png":
                                image.LoadImage(ms);
                                image.SavePng(ms);

                                break;

                            case "gif":
                                image.LoadImage(ms);
                                image.SaveGif(ms);
                                break;

                            case "bmp":
                                image.LoadImage(ms);
                                image.SaveBmp(ms);
                                break;

                            default:
                                image.LoadImage(ms);
                                image.SaveJpg(ms, 100);
                                break;
                            }
                            file = ms.ToArray();
                        }
                    }
                }


                if (file != null && file.Length != 0 && Offset < file.Length)
                {
                    if (BufferSize > file.Length - Offset)
                    {
                        NumberByteReadSuccess = (uint)(file.Length - Offset);
                        System.Runtime.InteropServices.Marshal.Copy(file, (int)Offset, buffer, (int)NumberByteReadSuccess);
                    }
                    else
                    {
                        NumberByteReadSuccess = BufferSize;
                        System.Runtime.InteropServices.Marshal.Copy(file, (int)Offset, buffer, (int)BufferSize);
                    }
                    return(0);
                }
                else
                {
                    Console.WriteLine("Error param {0}", Node.fileName);
                    return(0xC000000F);
                }
            }
示例#13
0
        /// <summary>
        /// Tries to handle an incoming request.
        /// </summary>
        /// <param name="api">The current api</param>
        /// <param name="request">The incoming route request</param>
        /// <returns>The result</returns>
        public IResponse Handle(Api api, IRequest request)
        {
            var slug = request.Segments.Length > 1 ? request.Segments[1] : "";
            int?width = null, height = null;

            if (!String.IsNullOrWhiteSpace(slug))
            {
                var index = slug.LastIndexOf('.');

                if (index != -1)
                {
                    var name   = slug.Substring(0, index);
                    var ending = slug.Substring(index);

                    var segments = name.Split(new char[] { '_' });

                    if (segments.Length > 2)
                    {
                        height = Convert.ToInt32(segments[2]);
                    }
                    if (segments.Length > 1)
                    {
                        width = Convert.ToInt32(segments[1]);
                    }
                    slug = segments[0] + ending;
                }

                var media = api.Media.GetSingle(slug);

                if (media != null)
                {
                    var response = request.StreamResponse();
                    var data     = App.Media.Get(media);

                    if (data != null)
                    {
                        response.ContentType = media.ContentType;

                        if (width.HasValue)
                        {
                            using (var mem = new MemoryStream(data)) {
                                var image = new KalikoImage(mem);
                                var scale = height.HasValue ?
                                            (ScalingBase) new CropScaling(width.Value, height.Value) :
                                            (ScalingBase) new FitScaling(width.Value, Int32.MaxValue);

                                image = image.Scale(scale);
                                image.SavePng(response.OutputStream);
                            }
                        }
                        else
                        {
                            using (var writer = new BinaryWriter(response.OutputStream)) {
                                writer.Write(data);
                            }
                        }
                        return(response);
                    }
                }
            }
            return(null);
        }