public static string SplitGif(string path, string emoteName)
        {
            string resStr = "";
            string folder = Path.GetDirectoryName(path);


            MagickImageCollection coll = new MagickImageCollection();

            MagickImageCollection collo = new MagickImageCollection(path);

            for (int j = 0; j < collo.Count; j += 6)
            {
                coll.Add(collo[j]);
            }


            var len = coll.Count;
            List <List <FrameInfo> > gifs = new List <List <FrameInfo> >();

            //List<MagickImageCollection> gifs = new List<MagickImageCollection>();

            //var b = coll[0].ToBitmap();
            //const int div = 16;
            //int w = b.Width - (b.Width % div);
            //int h = b.Height - (b.Height % div);

            //if ((w / div) * (h / div) > 50)
            //{
            //    if (h > w)
            //    {
            //        //int diff = (224 - h);
            //        float d = (float)(7 * div) / h;
            //        h = (7 * div);
            //        w = (int)(w * d);
            //    }
            //    else
            //    {
            //        float d = (float)(7 * div) / w;
            //        w = (7 * div);
            //        h = (int)(h * d);
            //    }
            //}
            //w = w - (w % div);
            //h = h - (h % div);

            //int tilesX = w / div;
            //int tilesY = h / div;
            //int div = 16;
            //var w = 5 * div;
            //var h = 4 * div;

            //int tilesX = 5;
            //int tilesY = 4;
            //int numTiles = tilesX * tilesY;

            //for (int j = 0; j < numTiles; j++)
            //{
            //    //gifs.Add(new List<FrameInfo>());
            //    //var c = new MagickImageCollection();
            //    gifs.Add(new List<FrameInfo>());
            //}


            for (int j = 0; j < len; j++)
            {
                using (MagickImage img = new MagickImage(coll[j]))
                {
                    var delay = img.AnimationDelay;
                    SliceFrame(gifs, img, delay);
                    //img.Resize(w, h);
                    //var tiles = img.CropToTiles(div, div).ToArray();
                    //for (int k = 0; k < numTiles; k++)
                    //{
                    //    //gifs[k].Add(new FrameInfo(tiles[k].ToBitmap(),);
                    //    MagickImage m = new MagickImage(tiles[k]);
                    //    m.AnimationDelay = delay;
                    //    gifs[k].Add(m);
                    //}
                }
            }

            string newFolder = Path.Combine(folder, emoteName.ToUpper() + "_" + Guid.NewGuid().ToString().Substring(0, 4));

            Directory.CreateDirectory(newFolder);

            QuantizeSettings settings = new QuantizeSettings();

            settings.Colors = 128;
            for (int j = 0; j < gifs.Count; j++)
            {
                //gifs[j].Quantize(settings);
                //gifs[j].Optimize();
                //gifs[j].Write(Path.Combine(newFolder, $"{emoteName}{j}.gif"));
                //Todo: write

                using (MagickImageCollection mc = new MagickImageCollection()) {
                    for (int k = 0; k < len; k++)
                    {
                        var mi = new MagickImage(gifs[j][k].bmp);
                        mi.AnimationDelay = gifs[j][k].delay;
                        mc.Add(mi);
                        gifs[j][k].bmp.Dispose();
                    }
                    mc.Quantize(settings);
                    mc.Optimize();
                    mc.Write(Path.Combine(newFolder, $"{emoteName}{j}.gif"));
                }
            }

            int iter = 0;

            for (int y = 0; y < tilesH; y++)
            {
                for (int x = 0; x < tilesW; x++)
                {
                    resStr += $":{emoteName}{iter}:";
                    iter++;
                }
                resStr += Environment.NewLine;
            }

            if (resStr.Length > 0)
            {
                resStr = resStr.Substring(0, resStr.Length - 2);
                File.WriteAllText(Path.Combine(newFolder, "pasteable.txt"), resStr);
            }

            tilesW = 0;
            tilesH = 0;
            return(resStr);
            //Path.Combine(newFolder, $"{emoteName}{iter}.png")
        }
        public virtual byte[] ConvertToPcx([NotNull] Bitmap bitmap)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException(nameof(bitmap));
            }

            // TODO merge with Svg.Contrib.Render.EPL.EplTransformer.ConvertToPcx, Svg.Contrib.Render.EPL

            var width = bitmap.Width;
            var mod   = width % 8;

            if (mod > 0)
            {
                width += 8 - mod;
            }
            var height = bitmap.Height;

            MagickImage magickImage;

#if NETSTANDARD2_0
            using (var memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream,
                            bitmap.RawFormat);

                magickImage = new MagickImage(memoryStream);
            }
#else
            magickImage = new MagickImage(bitmap);
#endif

            using (magickImage)
            {
                if (mod > 0)
                {
                    var magickGeometry = new MagickGeometry(width,
                                                            height)
                    {
                        IgnoreAspectRatio = true
                    };
                    magickImage.Resize(magickGeometry);
                }

                if (magickImage.HasAlpha)
                {
                    magickImage.ColorAlpha(MagickColors.White);
                }

                var quantizeSettings = new QuantizeSettings
                {
                    Colors       = 2,
                    DitherMethod = DitherMethod.No
                };
                magickImage.Quantize(quantizeSettings);

                magickImage.ColorType = ColorType.Bilevel;
                magickImage.Depth     = 1;
                magickImage.Format    = MagickFormat.Pcx;

                magickImage.Density = new Density(bitmap.HorizontalResolution,
                                                  bitmap.VerticalResolution);

                magickImage.Negate(); // TODO see https://github.com/dlemstra/Magick.NET/issues/569

                var array = magickImage.ToByteArray();

                array = this.StripExtendedColorPaletteFromPcx(array);

                return(array);
            }
        }
Beispiel #3
0
        public string CreateAnimatedGif(int gameId, string tempAnimatedGif)
        {
            try
            {
                var game = _dataContext.Game.FirstOrDefault(x => x.Id == gameId);

                using (var magickImageCollection = new MagickImageCollection())
                {
                    var startingWordImage   = TextToImageConversion.CreateBitmapImage("Start: " + game.StartingWord);
                    var startingMagickImage = new MagickImage(startingWordImage)
                    {
                        AnimationDelay = 300
                    };
                    magickImageCollection.Add(startingMagickImage);

                    var count = 1;
                    foreach (var guess in game.Guesses)
                    {
                        if (guess is WordGuess)
                        {
                            var wordGuess = (WordGuess)guess;

                            String word;
                            if (game.Guesses.Count == count)
                            {
                                word = "Final: " + wordGuess.Word;
                            }
                            else
                            {
                                word = count + ": " + wordGuess.Word;
                            }

                            var magickWordImage = new MagickImage(TextToImageConversion.CreateBitmapImage(word))
                            {
                                AnimationDelay = 300
                            };
                            magickImageCollection.Add(magickWordImage);
                        }
                        else if (guess is ImageGuess)
                        {
                            var   imageGuess = (ImageGuess)guess;
                            Image image;
                            using (var webClient = new WebClient())
                            {
                                image = Image.FromStream(webClient.OpenRead(imageGuess.Image));
                            }

                            var magickImage = new MagickImage((Bitmap)image)
                            {
                                AnimationDelay = 300
                            };
                            magickImageCollection.Add(magickImage);
                        }
                        count++;
                    }

                    var settings = new QuantizeSettings {
                        Colors = 256
                    };
                    foreach (var magickImage in magickImageCollection)
                    {
                        MagickGeometry geometry = new MagickGeometry(1024, 1024);
                        geometry.IgnoreAspectRatio = true;
                        magickImage.Resize(geometry);

                        //magickImage.Resize(new MagickGeometry("1024x1024!"));
                    }
                    magickImageCollection.Quantize(settings);

                    //We can't optimize if the images are not all the same dimensions
                    magickImageCollection.Optimize();

                    magickImageCollection.Write(tempAnimatedGif);
                }

                game.AnimatedResult = _cloudImageService.SaveImageToCloud(tempAnimatedGif, gameId.ToString() + ".gif");
                _dataContext.Commit();
                return(game.AnimatedResult);
            }
            catch (Exception e)
            {
                throw;
            }
        }
Beispiel #4
0
        public async Task <bool> Execute(IWorkspace workspace, object arg = null)
        {
            // get entities
            var entities = await workspace.InputService.GetEntities();

            if (entities.Cancel || !entities.HasValue)
            {
                return(false);
            }

            if (!entities.Value.Any())
            {
                return(true);
            }

            // get distance quantum
            var distance = await workspace.InputService.GetDistance(new UserDirective("Distance quantum"), defaultDistance : LastDistanceQuantum);

            if (distance.Cancel)
            {
                return(false);
            }

            double distanceQuantum;

            if (distance.HasValue)
            {
                distanceQuantum = distance.Value;
            }
            else
            {
                distanceQuantum = LastDistanceQuantum;
            }

            LastDistanceQuantum = distanceQuantum;

            // get angle quantum
            var angle = await workspace.InputService.GetDistance(new UserDirective("Angle quantum"), defaultDistance : LastAngleQuantum);

            if (angle.Cancel)
            {
                return(false);
            }

            double angleQuantum;

            if (angle.HasValue)
            {
                angleQuantum = angle.Value;
            }
            else
            {
                angleQuantum = LastAngleQuantum;
            }

            LastAngleQuantum = angleQuantum;

            // do it
            var settings = new QuantizeSettings(distanceQuantum, angleQuantum);
            var drawing  = workspace.Drawing;

            foreach (var entity in entities.Value)
            {
                var quantized     = EditUtilities.Quantize(entity, settings);
                var layer         = drawing.ContainingLayer(entity);
                var originalLayer = layer;
                layer   = layer.Remove(entity);
                layer   = layer.Add(quantized);
                drawing = drawing.Remove(originalLayer);
                drawing = drawing.Add(layer);
            }

            workspace.Update(drawing: drawing);

            return(true);
        }
        private void button_SaveAnimation_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            //openFileDialog.InitialDirectory = subPath;
            saveFileDialog.Filter   = "GIF Files: (*.gif)|*.gif";
            saveFileDialog.FileName = "Preview.gif";
            //openFileDialog.Filter = "Binary File (*.bin)|*.bin";
            ////openFileDialog1.FilterIndex = 2;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.Title            = Properties.FormStrings.Dialog_Title_SaveGIF;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                Bitmap bitmap = new Bitmap(Convert.ToInt32(454), Convert.ToInt32(454), PixelFormat.Format32bppArgb);
                Bitmap mask   = new Bitmap(Application.StartupPath + @"\Mask\mask_gtr47.png");
                if (Model_Wath.model_gtr42)
                {
                    bitmap = new Bitmap(Convert.ToInt32(390), Convert.ToInt32(390), PixelFormat.Format32bppArgb);
                    mask   = new Bitmap(Application.StartupPath + @"\Mask\mask_gtr42.png");
                }
                if (Model_Wath.model_gts)
                {
                    bitmap = new Bitmap(Convert.ToInt32(348), Convert.ToInt32(442), PixelFormat.Format32bppArgb);
                    mask   = new Bitmap(Application.StartupPath + @"\Mask\mask_gts.png");
                }
                if (Model_Wath.model_TRex || Model_Wath.model_Verge)
                {
                    bitmap = new Bitmap(Convert.ToInt32(360), Convert.ToInt32(360), PixelFormat.Format32bppArgb);
                    mask   = new Bitmap(Application.StartupPath + @"\Mask\mask_trex.png");
                }
                if (Model_Wath.model_AmazfitX)
                {
                    bitmap = new Bitmap(Convert.ToInt32(206), Convert.ToInt32(640), PixelFormat.Format32bppArgb);
                    mask   = new Bitmap(Application.StartupPath + @"\Mask\mask_Amazfitx.png");
                }
                Graphics gPanel   = Graphics.FromImage(bitmap);
                bool     save     = false;
                int      set      = 0;
                int      oldSet   = -1;
                int      setIndex = 0;
                Random   rnd      = new Random();
                progressBar_SaveAnimation.Width   = pictureBox_AnimatiomPreview.Width - 100;
                progressBar_SaveAnimation.Maximum = (int)numericUpDown_NumberOfFrames.Value;
                progressBar_SaveAnimation.Value   = 0;
                progressBar_SaveAnimation.Visible = true;
                Form1 form1 = this.Owner as Form1;//Получаем ссылку на первую форму
                form1.PreviewView = false;
                timer1.Enabled    = false;
                foreach (ClassMotiomAnimation elementMotiomAnimation in MotiomAnimation)
                {
                    elementMotiomAnimation.ResetDrawMotiomAnimation();
                }
                if (StaticAnimation != null)
                {
                    StaticAnimation.ResetDrawStaticAnimation();
                }

                using (MagickImageCollection collection = new MagickImageCollection())
                {
                    int WeatherSet_Temp      = (int)form1.numericUpDown_WeatherSet_Temp.Value;
                    int WeatherSet_DayTemp   = (int)form1.numericUpDown_WeatherSet_DayTemp.Value;
                    int WeatherSet_NightTemp = (int)form1.numericUpDown_WeatherSet_NightTemp.Value;
                    int WeatherSet_Icon      = form1.comboBox_WeatherSet_Icon.SelectedIndex;

                    for (int i = 0; i < numericUpDown_NumberOfFrames.Value; i++)
                    {
                        save = false;
                        while (!save)
                        {
                            switch (set)
                            {
                            case 0:
                                //button_Set1.PerformClick();
                                form1.SetPreferences1();
                                save = true;
                                break;

                            case 1:
                                if (form1.numericUpDown_Calories_Set2.Value != 1234)
                                {
                                    //button_Set2.PerformClick();
                                    form1.SetPreferences2();
                                    save = true;
                                }
                                break;

                            case 2:
                                if (form1.numericUpDown_Calories_Set3.Value != 1234)
                                {
                                    //button_Set3.PerformClick();
                                    form1.SetPreferences3();
                                    save = true;
                                }
                                break;

                            case 3:
                                if (form1.numericUpDown_Calories_Set4.Value != 1234)
                                {
                                    //button_Set4.PerformClick();
                                    form1.SetPreferences4();
                                    save = true;
                                }
                                break;

                            case 4:
                                if (form1.numericUpDown_Calories_Set5.Value != 1234)
                                {
                                    //button_Set5.PerformClick();
                                    form1.SetPreferences5();
                                    save = true;
                                }
                                break;

                            case 5:
                                if (form1.numericUpDown_Calories_Set6.Value != 1234)
                                {
                                    //button_Set6.PerformClick();
                                    form1.SetPreferences6();
                                    save = true;
                                }
                                break;

                            case 6:
                                if (form1.numericUpDown_Calories_Set7.Value != 1234)
                                {
                                    //button_Set7.PerformClick();
                                    form1.SetPreferences7();
                                    save = true;
                                }
                                break;

                            case 7:
                                if (form1.numericUpDown_Calories_Set8.Value != 1234)
                                {
                                    //button_Set8.PerformClick();
                                    form1.SetPreferences8();
                                    save = true;
                                }
                                break;

                            case 8:
                                if (form1.numericUpDown_Calories_Set9.Value != 1234)
                                {
                                    //button_Set9.PerformClick();
                                    form1.SetPreferences9();
                                    save = true;
                                }
                                break;

                            case 9:
                                if (form1.numericUpDown_Calories_Set10.Value != 1234)
                                {
                                    //button_Set10.PerformClick();
                                    form1.SetPreferences10();
                                    save = true;
                                }
                                break;

                            case 10:
                                if (form1.numericUpDown_Calories_Set11.Value != 1234)
                                {
                                    //button_Set11.PerformClick();
                                    form1.SetPreferences11();
                                    save = true;
                                }
                                break;

                            case 11:
                                if (form1.numericUpDown_Calories_Set12.Value != 1234)
                                {
                                    //button_Set12.PerformClick();
                                    form1.SetPreferences12();
                                    save = true;
                                }
                                break;

                            case 12:
                                if (form1.numericUpDown_Calories_Set13.Value != 1234)
                                {
                                    //button_Set13.PerformClick();
                                    form1.SetPreferences13();
                                    save = true;
                                }
                                break;
                            }
                            if (!save)
                            {
                                set++;
                            }
                            if (set > 12)
                            {
                                set = 0;
                            }
                        }

                        if (save)
                        {
                            if (oldSet != set)
                            {
                                form1.numericUpDown_WeatherSet_Temp.Value      = rnd.Next(-25, 35) + 1;
                                form1.numericUpDown_WeatherSet_DayTemp.Value   = form1.numericUpDown_WeatherSet_Temp.Value;
                                form1.numericUpDown_WeatherSet_NightTemp.Value = form1.numericUpDown_WeatherSet_Temp.Value - rnd.Next(3, 10);
                                form1.comboBox_WeatherSet_Icon.SelectedIndex   = rnd.Next(0, 25);
                                oldSet = set;
                            }

                            form1.PreviewToBitmap(gPanel, 1.0f, false, false, false, false, false, false, false, false, false, 1);

                            foreach (ClassMotiomAnimation elementMotiomAnimation in MotiomAnimation)
                            {
                                elementMotiomAnimation.DrawMotiomAnimation(gPanel, 100);
                            }
                            if (StaticAnimation != null)
                            {
                                StaticAnimation.DrawStaticAnimation(gPanel, 100);
                            }
                            form1.PreviewToBitmap(gPanel, 1.0f, false, false, false, false, false, false, false, false, false, 2);

                            if (form1.checkBox_crop.Checked)
                            {
                                bitmap = form1.ApplyMask(bitmap, mask);
                                gPanel = Graphics.FromImage(bitmap);
                            }
                            // Add first image and set the animation delay to 100ms
                            MagickImage item = new MagickImage(bitmap);
                            //ExifProfile profile = item.GetExifProfile();
                            collection.Add(item);
                            //collection[collection.Count - 1].AnimationDelay = 100;
                            collection[collection.Count - 1].AnimationDelay = 10;
                        }

                        setIndex = setIndex + 100;
                        if (setIndex >= (1000 * form1.numericUpDown_Gif_Speed.Value))
                        {
                            setIndex = 0;
                            set++;
                            if (set > 12)
                            {
                                set = 0;
                            }
                        }

                        progressBar_SaveAnimation.Value = i;
                        progressBar_SaveAnimation.Update();
                    }

                    form1.numericUpDown_WeatherSet_Temp.Value      = WeatherSet_Temp;
                    form1.numericUpDown_WeatherSet_DayTemp.Value   = WeatherSet_DayTemp;
                    form1.numericUpDown_WeatherSet_NightTemp.Value = WeatherSet_NightTemp;
                    form1.comboBox_WeatherSet_Icon.SelectedIndex   = WeatherSet_Icon;


                    progressBar_SaveAnimation.Visible = false;
                    // Optionally reduce colors
                    QuantizeSettings settings = new QuantizeSettings();
                    //settings.Colors = 256;
                    //collection.Quantize(settings);

                    // Optionally optimize the images (images should have the same size).
                    collection.OptimizeTransparency();
                    //collection.Optimize();

                    // Save gif
                    collection.Write(saveFileDialog.FileName);
                }
                form1.PreviewView = true;
                timer1.Enabled    = true;
                mask.Dispose();
            }
        }
Beispiel #6
0
        public async Task Progress()
        {
            var author = Context.Message.Author;

            if (author.Id != Program.ApplicationSetting.Owner)
            {
                Context.Channel.SendMessageAsync("You aren't allowed to run this command", false);
                return;
            }

            (string basePath, string baseOutputPath) = MovieHelper.CleanAndCreateMovieFolders();

            SKRect rect = new SKRect(100, 100, 200, 200);

            var arcPaint = new SKPaint()
            {
                Color = new SKColor(255, 0, 0)
            };

            List <Task> tasks = new List <Task>();

            // draw empty rectabgle
            int frame = 0;

            // Spawn the border
            for (int i = 0; i < 10; i++)
            {
                var drawInfo = DrawingHelper.GetEmptyGraphics(505, 200);


                drawInfo.Canvas.DrawRect(70, 25, 365, 100, new SKPaint()
                {
                    Color = new SKColor(255, 0, 0, (byte)(20 * i + 30)), IsStroke = true, Style = SKPaintStyle.Stroke, StrokeWidth = 4
                });

                tasks.Add(MovieHelper.SaveToDisk(basePath, frame, drawInfo.Bitmap, drawInfo.Canvas));
                frame++;
            }

            // Standstill
            for (int i = 0; i < 5; i++)
            {
                var drawInfo = DrawingHelper.GetEmptyGraphics(505, 200);

                drawInfo.Canvas.DrawRect(70, 25, 365, 100, new SKPaint()
                {
                    Color = new SKColor(255, 0, 0, 255), IsStroke = true, Style = SKPaintStyle.Stroke, StrokeWidth = 4
                });

                tasks.Add(MovieHelper.SaveToDisk(basePath, frame, drawInfo.Bitmap, drawInfo.Canvas));
                frame++;
            }

            int dayOfTheYear = 60; Math.Min(DateTime.Now.DayOfYear, 365); // dont handle leap years for now TODO

            for (int i = 0; i < dayOfTheYear + 10; i++)
            {
                var drawInfo = DrawingHelper.GetEmptyGraphics(505, 200);

                for (int j = 0; j < Math.Min(i, 10); j++)
                {
                    drawInfo.Canvas.DrawRect(70, 23, Math.Min(i - j, dayOfTheYear), 100, new SKPaint()
                    {
                        Color = new SKColor(0, 255, 0, 25), Style = SKPaintStyle.Fill
                    });

                    if (j == i)
                    {
                        break;
                    }
                }

                // border
                drawInfo.Canvas.DrawRect(70, 25, 365, 100, new SKPaint()
                {
                    Color = new SKColor(255, 0, 0, 255), IsStroke = true, Style = SKPaintStyle.Stroke, StrokeWidth = 4
                });

                tasks.Add(MovieHelper.SaveToDisk(basePath, frame, drawInfo.Bitmap, drawInfo.Canvas));
                frame++;
            }


            /*            for (int i = 0; i < 180; i++)
             *  {
             *      var drawInfo = DrawingHelper.GetEmptyGraphics(500, 500);
             *
             *      using (SKPath path = new SKPath())
             *      {
             *          path.AddArc(rect, 0, i);
             *          drawInfo.Canvas.DrawPath(path, arcPaint);
             *
             *          tasks.Add(SaveToDisk(basePath, i, drawInfo.Bitmap, drawInfo.Canvas));
             *      }
             *  }*/

            int random = new Random().Next(1_000_000_000);

            var    files    = Directory.GetFiles(Path.Combine(basePath)).ToList().OrderBy(i => i);
            string fileName = Path.Combine(baseOutputPath, $"movie_{random}.gif");

            try
            {
                using (var collection = new MagickImageCollection())
                {
                    int i = 0;
                    foreach (var file in files)
                    {
                        collection.Add(file);
                        collection[i].AnimationDelay = 1; // in this example delay is 1000ms/1sec

                        if (i == 0)
                        {
                            collection[i].AnimationIterations = 0;
                        }

                        //collection[i].Flip();
                        i++;
                    }

                    // Optionally reduce colors
                    var settings = new QuantizeSettings();

                    //settings.Colors = 256;
                    //collection.Quantize(settings);

                    // Optionally optimize the images (images should have the same size).
                    //collection.Optimize();

                    // Save gif
                    collection.Write(fileName, MagickFormat.Gif);
                }
            }
            catch (Exception ex)
            {
            }

            await Context.Channel.SendFileAsync(fileName);
        }
Beispiel #7
0
        public IActionResult Get(int id, [FromQuery] int width = 25, [FromQuery] int height = 25)
        {
            Random r = new Random(id);

            var allAlgs = _algorithms;
            var alg     = allAlgs.ElementAt(r.Next(allAlgs.Count()));
            var runs    = new List <AlgorithmRun>
            {
                new AlgorithmRun()
                {
                    Alg     = alg.Clone() as IAlgorithm,
                    Context = new AlgorithmContextBase()
                    {
                        R = new AlgorithmRandom(id)
                    }
                }
            };

            var renderer = new DungeonTileRenderer();

            renderer.ShadeGroups = false;
            var generator  = new DungeonGenerator();
            var stepImages = new List <Image>();
            var collection = new MagickImageCollection();
            var counter    = 0;

            Action <IAlgorithmContext> RenderAction = new Action <IAlgorithmContext>((context) =>
            {
                if (counter++ % 5 != 0)
                {
                    return;
                }

                var d   = context.D;
                var img = renderer.Render(d);

                AddImageToCollection(img, collection, 5);
            });

            generator.Options = new DungeonGenerator.DungeonGeneratorOptions()
            {
                DoReset           = true,
                EgressConnections = null,
                Width             = width,
                Height            = height,
                AlgRuns           = runs,
                Callbacks         =
                {
                    RenderAction
                }
            };

            try
            {
                var dungeon   = generator.Generate();
                var lastImage = renderer.Render(dungeon);
                AddImageToCollection(lastImage, collection, 500);

                var gif_ms = new MemoryStream();
                collection.First().AnimationIterations = 0;
                var magickSettings = new QuantizeSettings();
                magickSettings.Colors = 256;
                collection.Quantize(magickSettings);
                collection.Optimize();
                collection.Write(gif_ms, MagickFormat.Gif);
                gif_ms.Seek(0, SeekOrigin.Begin);

                var ms = new MemoryStream();
                lastImage.Save(ms, ImageFormat.Png);
                ms.Seek(0, SeekOrigin.Begin);

                var jsonObj = new
                {
                    alt        = "A DunGenImage",
                    algorithm  = alg.Name,
                    imageBytes = ms.GetBuffer(),
                    gifBytes   = gif_ms.GetBuffer()
                };

                return(Ok(jsonObj));
            }
            catch (NotImplementedException)
            {
                return(NotFound(String.Format("{0} is not implemented.", alg.Name)));
            }
            catch (Exception e)
            {
                var message = new StringBuilder();
                message.AppendLine("Something went wrong. Exception details:");
                while (e != null)
                {
                    message.AppendFormat("\"{0}\"\n", e.Message);
                    message.AppendLine(e.StackTrace);
                    message.AppendLine(e.InnerException != null ? "Inner Exception:" : "");
                    e = e.InnerException;
                }
                return(NotFound(message.ToString()));
            }
        }
        public FREObject ResizeImage(FREContext ctx, uint argc, FREObject[] argv)
        {
            // Read from file



            try {
                var newW  = Convert.ToInt32(new FreObjectSharp(argv[1]).Value);
                var newH  = Convert.ToInt32(new FreObjectSharp(argv[2]).Value);
                var array = new FREArray(new FreObjectSharp(argv[0]).RawValue);
                var list  = array.ToArrayList();

                using (MagickImageCollection collection = new MagickImageCollection())
                {
                    string outputDir = "";
                    int    i         = 0;
                    foreach (String inputPath in list)
                    {
                        FileInfo input = new FileInfo(inputPath);
                        outputDir = input.Directory.CreateSubdirectory("small").FullName;
                        FileInfo output = new FileInfo(outputDir + @"\" + input.Name);


                        try
                        {
                            using (MagickImage image = new MagickImage(input))
                            {
                                MagickGeometry size = new MagickGeometry(newW, newH);
                                //image.Resize(size);  genera un ciclo infinito en v84
                                image.AdaptiveResize(size);
                                // Save the result
                                image.Write(output.FullName);
                                collection.Add(output.FullName);
                                collection[i].AnimationDelay = 200;
                            }
                        }
                        // Catch any MagickException
                        catch (MagickException exception)
                        {
                            // Write excepion raised when reading the invalid jpg to the console
                            Trace("ERROR: " + exception);
                            return(new FreException(exception).RawValue);
                        }


                        i++;
                    }

                    // Optionally reduce colors
                    QuantizeSettings settings = new QuantizeSettings();
                    settings.Colors = 256;
                    collection.Quantize(settings);

                    // Optionally optimize the images (images should have the same size).
                    collection.Optimize();
                    // Save gif
                    collection.Write(outputDir + @"\output.gif");

                    return(new FreObjectSharp(outputDir + @"\output.gif").RawValue);
                }
            }

            catch (Exception e) {
                Trace("Exception " + e);
            }

            return(FREObject.Zero);
        }