private MagickImage BuildImageWithPadding(MagickImage source)
        {
            int tilesWide = source.Width / Settings.TileX;
            int tilesHigh = source.Height / Settings.TileY;

            int newImageWidth  = source.Width + Settings.PaddingX * tilesWide * 2;
            int newImageHeight = source.Height + Settings.PaddingY * tilesHigh * 2;

            MagickImage result = new MagickImage(MagickColors.Transparent, newImageWidth, newImageHeight);

            IMagickImage <ushort>[]? tiles = source.CropToTiles(Settings.TileX, Settings.TileY).ToArray();

            for (int y = 0; y < tilesHigh; y++)
            {
                Progress.Report((int)(100 * ((float)(y + 1) / tilesHigh)));
                for (int x = 0; x < tilesWide; x++)
                {
                    using var subImage   = tiles[x + y * tilesWide];
                    subImage.BorderColor = MagickColors.Transparent;
                    subImage.Border(Settings.PaddingX, Settings.PaddingY);
                    using var subImagePixels = subImage.GetPixels();

                    ExtendEdge(subImagePixels, subImage.Width, subImage.Height);
                    result.Composite(subImage, x * subImage.Width, y * subImage.Height, CompositeOperator.SrcOver);
                }
            }

            return(result);
        }
Exemplo n.º 2
0
        private PdfShot GetPdfDocument(Image fullPageImage, ShotOptions options, String title)
        {
            var magicImage = new MagickImage(fullPageImage.ToMemoryStream());

            magicImage.Strip();

            if (options.IsGrayscale)
            {
                magicImage.Grayscale(PixelIntensityMethod.Lightness);
                magicImage.Contrast();
            }

            var partsCount = Math.Ceiling((Decimal)magicImage.Height / options.StepHeight);

            partsCount = Math.Ceiling((magicImage.Height + options.OverlaySize * partsCount) / options.StepHeight);

            var pageImageParts = new List <Byte[]>();

            for (var i = 0; i < partsCount; i++)
            {
                var y      = i * options.StepHeight - i * options.OverlaySize;
                var images = magicImage.CropToTiles(new MagickGeometry(0,
                                                                       y,
                                                                       options.Width,
                                                                       options.StepHeight))
                             .ToList();
                pageImageParts.Add(images.First().ToByteArray());
            }

            var pdfBytes = _pdfCreator.CreateDocument(options.Width, options.StepHeight, pageImageParts);

            return(new PdfShot(pdfBytes, GetFileName(title)));
        }
Exemplo n.º 3
0
        public IEnumerable <Tuple <Terrain, Tuple <int, int> > > GetTilemapAsTerrain(int tmap_num)
        {
            string directory;

            if (ApplicationSettings.Instance.ActiveProject.Type == ProjectType.AdventureMode)
            {
                directory = Path.Combine(Path.GetDirectoryName(ApplicationSettings.Instance.ActiveProject.ProjectPath), "sprites", "articles");
            }
            else
            {
                directory = Path.Combine(Path.GetDirectoryName(ApplicationSettings.Instance.ActiveProject.ProjectPath), "sprites");
            }

            MagickImage tileset = new MagickImage(Path.Combine(directory, Tileset.SpritePath + ".png"));
            List <IMagickImage <ushort> > tiles = tileset.CropToTiles(Tileset.TileWidth, Tileset.TileHeight).ToList();

            // Define the bounds of the tilemap in this cell
            int tl_x = Tilegrid.MinX * TilegridArray.ChunkSizeX, tl_y = Tilegrid.MinY * TilegridArray.ChunkSizeY, br_x = tl_x, br_y = tl_y;
            int max_x    = Tilegrid.MaxX * TilegridArray.ChunkSizeX + TilegridArray.ChunkSizeX;
            int max_y    = Tilegrid.MaxY * TilegridArray.ChunkSizeY + TilegridArray.ChunkSizeY;
            var min_cell = IndexToCell(tl_x, tl_y);
            var max_cell = IndexToCell(max_x, max_y);

            for (int y = min_cell.Item2; y <= max_cell.Item2; y++)
            {
                for (int x = min_cell.Item1; x <= max_cell.Item1; x++)
                {
                    var maxIndex = MaxIndexInCell(x, y);
                    br_x = maxIndex.Item1 < max_x ? maxIndex.Item1 : max_x;
                    br_y = maxIndex.Item2 < max_y ? maxIndex.Item2 : max_y;

                    if (BuildTerrain(tl_x, tl_y, br_x, br_y, x, y, tmap_num, directory, tiles, out Terrain terrain))
                    {
                        yield return(Tuple.Create(terrain, Tuple.Create(x, y)));
                    }

                    tl_x = br_x + 1;
                }

                // Shift the top of our cell 1 tile down
                tl_y = br_y + 1;
                // Reset x pos
                tl_x = Tilegrid.MinX * TilegridArray.ChunkSizeX;
            }
        }
Exemplo n.º 4
0
        private static void SliceImage(string inputPath)
        {
            var originalFileDir  = Path.GetDirectoryName(inputPath);
            var originalFileName = Path.GetFileNameWithoutExtension(inputPath);
            var originalFileExt  = Path.GetExtension(inputPath);

            using (var image = new MagickImage(inputPath))
            {
                int i = 0;
                var bestImageHeight = GetBestImageHeight(image);
                var outputDir       = $"{originalFileDir}\\PoOutput";
                EmptyOutputDirectory(outputDir);
                foreach (MagickImage tile in image.CropToTiles(image.Width, bestImageHeight))
                {
                    tile.Write($"{outputDir}\\{originalFileName}_{i++}.jpg");
                }
            }
        }
Exemplo n.º 5
0
        public static async Task Tile(string path, int tileW, int tileH, bool useTileAmount, bool delSrc)
        {
            MagickImage img = IOUtils.ReadImage(path);

            if (img == null)
            {
                return;
            }
            PreProcessing(path);

            string pathNoExt = Path.ChangeExtension(path, null);
            string ext       = Path.GetExtension(path);

            if (useTileAmount)
            {
                tileW = (int)Math.Round(img.Width / (float)tileW);
                tileH = (int)Math.Round(img.Height / (float)tileH);
            }

            int i = 1;

            Program.Print("-> Creating tiles...");
            var tiles = img.CropToTiles(tileW, tileH);

            foreach (MagickImage tile in tiles)
            {
                tile.Write(pathNoExt + "-tile" + i + ext);
                Program.Print("-> Saved tile " + i + "/" + tiles.Count(), true);
                i++;
                if (i % 2 == 0)
                {
                    await Program.PutTaskDelay();
                }
            }
            await Program.PutTaskDelay();

            PostProcessing(img, path);
            if (delSrc)
            {
                DelSource(path);
            }
        }
        private void writeAFewTilesToOutputFile(string pathOfInputGif)
        {
            //Write multiple tiles taken from input file to
            //a single output file - mark one
            string nameOfGifForOutputCompositeGif = "TEMP-TEST-COMPOSITE-OUTPUT-{0}-" + System.Guid.NewGuid() + "-{1}";
            string pathToTemp = Path.GetTempPath();

            ql(String.Format("About to start writing multiple tiles to a single file (mark 1). Tile width : {0} and tile height : {1}.", TILEWIDTHSIZE, TILEHEIGHTSIZE));
            using (var image = new MagickImage(pathOfInputGif))
            {
                IEnumerable <IMagickImage <byte> > enumerableTiles = image.CropToTiles(TILEWIDTHSIZE, TILEHEIGHTSIZE);
                List <IMagickImage <byte> >        lstTiles        = enumerableTiles.ToList <IMagickImage <byte> >();
                string pathCompositeImageOut = Path.Combine(pathToTemp, String.Format(nameOfGifForOutputCompositeGif, 99999.ToString("D5"), TESTIMAGE_OBFUSCATED));
                ql(String.Format("Composite output at {0}", pathCompositeImageOut));
                var imageout = new MagickImage(MagickColors.Red, image.Width, image.Height);
                imageout.Composite(lstTiles[4], 20, 20);
                imageout.Composite(lstTiles[8], 100, 100);
                imageout.Write(pathCompositeImageOut);
            }
        }
        private void writeInputToMultipleTileFiles(string pathOfInputGif)
        {
            //Write multiple tiles taken from input file to
            //multiple output files
            string pathToTemp = Path.GetTempPath();
            string nameOfGifForOutputTileGif = "TEMP-TEST-TILE-OUTPUT-{0}-{1}-{2}";
            string guidForOutputTileGif      = System.Guid.NewGuid().ToString();

            ql(String.Format("About to start making files from tiles. Tile width : {0} and tile height : {1}.", TILEWIDTHSIZE, TILEHEIGHTSIZE));

            using (var image = new MagickImage(pathOfInputGif))
            {
                int i = 1;
                foreach (MagickImage tile in image.CropToTiles(TILEWIDTHSIZE, TILEHEIGHTSIZE))
                {
                    string pathTileImageOut = Path.Combine(pathToTemp, String.Format(nameOfGifForOutputTileGif, i.ToString("D5"), guidForOutputTileGif, TESTIMAGE_OBFUSCATED));
                    tile.Write(pathTileImageOut);
                    i++;
                }
            }
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            IDictionary <string, string> layout = new Dictionary <string, string>()
            {
                { "Title", "00" },
                { "User ID", "2A" },
                { "User Name", "3F" },
                { "Town ID", "40" },
                { "Town Name", "42" },
                { "Palette", "58" },
                { "Pattern Type", "69" },
                { "Data", "6C" }
            };

            var file = File.ReadAllText("./test.acnl", Encoding.UTF8);

            Console.WriteLine($"\nRaw: {file}");

            var title    = file.Substring(int.Parse(layout["Title"], NumberStyles.HexNumber), 42);
            var userId   = file.Substring(int.Parse(layout["User ID"], NumberStyles.HexNumber), 2);
            var userName = file.Substring(int.Parse(layout["User Name"], NumberStyles.HexNumber), 20);
            var townId   = file.Substring(int.Parse(layout["Town ID"], NumberStyles.HexNumber), 2);
            var townName = file.Substring(int.Parse(layout["Town Name"], NumberStyles.HexNumber), 20);

            Console.WriteLine($"Title: {title}");
            Console.WriteLine($"UserID: {userId}");
            Console.WriteLine($"User Name: {userName}");
            Console.WriteLine($"Town ID: {townId}");
            Console.WriteLine($"Town Name: {townName}");

            // Convert image to AC friendly

            using var image = new MagickImage("./bliss.png");

            // Crop and resize

            var geometry = new MagickGeometry(128, 128);

            geometry.FillArea = true;
            image.Resize(geometry);
            image.Crop(128, 128, Gravity.Center);
            image.RePage();

            image.Quantize(new QuantizeSettings {
                Colors = 15, DitherMethod = DitherMethod.FloydSteinberg
            });

            var colors = GenerateColorProfileImage();

            try
            {
                image.Map(colors, new QuantizeSettings {
                    Colors = 15, DitherMethod = DitherMethod.No
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex}");
                return;
            }

            // Build Palette

            var matchedColors = image.Histogram();

            var palleteString = string.Empty;

            foreach (var(key, _) in matchedColors)
            {
                var inGameValue = ColorStrings.Dictionary[key.ToString()];
                // Array.Reverse(inGameValue);
                // var reversedValue = string.Concat(inGameValue);
                palleteString += inGameValue;
            }

            var finalPalleteString = palleteString.PadRight(30, '0');

            Console.Write(finalPalleteString);

            // TODO: Tile and generate strings

            var index = 1;

            foreach (var tile in image.CropToTiles(32, 32))
            {
                // TODO: iterate over pixels, create string and complete file
            }

            // TODO: Produce QR Codes
        }
Exemplo n.º 9
0
        public MagickImageCollection GenerateQrCodes()
        {
            // TODO: Shape to the image ratio
            var geometry = new MagickGeometry(128, 128)
            {
                FillArea = true
            };

            _image.Resize(geometry);
            _image.Crop(128, 128, Gravity.Center);
            _image.RePage();

            _image.Quantize(new QuantizeSettings {
                Colors = 15, DitherMethod = DitherMethod.FloydSteinberg
            });

            var colors = GenerateColorProfileImage();

            try
            {
                _image.Map(colors, new QuantizeSettings {
                    Colors = 15, DitherMethod = DitherMethod.No
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex}");
                return(new MagickImageCollection());
            }

            var(paletteString, paletteIndex) = GeneratePaletteInfo(_image);

            var qrCodes = new MagickImageCollection();

            foreach (var tile in _image.CropToTiles(32, 32))
            {
                var leftSide  = new List <string>();
                var rightSide = new List <string>();

                using (var pixels = tile.GetPixels())
                {
                    foreach (var pixel in pixels)
                    {
                        var x = paletteIndex[pixel.ToColor().ToString()].ToString("X");
                        if (pixel.X % 2 == 0)
                        {
                            rightSide.Add(x);
                        }
                        else
                        {
                            leftSide.Add(x);
                        }
                    }
                }

                var zipped = leftSide.Zip(rightSide, (l, r) => $"{l}{r}").ToArray();

                var pixelString = string.Join("", zipped);

                var output     = PatternStringBuilder.Build(paletteString, pixelString);
                var byteOutput = StringToByteArray(output);

                // var qrGenerator = new QRCodeGenerator();
                // var qrCodeData = qrGenerator.CreateQrCode(byteOutput, QRCodeGenerator.ECCLevel.M);
                // var qrCode = new QRCode(qrCodeData);
                // var qrCodeImage = qrCode.GetGraphic(4);
                // qrCodes.Add(qrCodeImage);


                var qrGenerator = new QRCodeGenerator();
                var qrCodeData  = qrGenerator.CreateQrCode(byteOutput, QRCodeGenerator.ECCLevel.M);
                var qrCode      = new BitmapByteQRCode(qrCodeData);
                var qrCodeImage = qrCode.GetGraphic(4);
                using (var ms = new MemoryStream(qrCodeImage, 0, qrCodeImage.Length))
                {
                    qrCodes.Add(new MagickImage(ms));
                };
            }

            return(qrCodes);
        }
        private string deObfuscateImage(ObfuscationMode obfMode, string pathOfInputGif, string strGuid)
        {
            string         pathToTemp = Path.GetTempPath();
            string         nameOfGifForOutputCompositeGif;
            int            pixelYDestination;
            int            pixelXDestination;
            DateTimeOffset now         = DateTimeOffset.UtcNow;
            string         strUtcTicks = now.UtcTicks.ToString();
            string         iso         = DateTime.UtcNow.ToString("yyyy.MM.ddTHH.mm.ss.fffff");

            if (obfMode == ObfuscationMode.DEOBFUSCATE)
            {
                nameOfGifForOutputCompositeGif = "{0}-TEMP-TEST-COMPOSITE-DEOBFUSCATE-OUTPUT-{1}-" + strGuid + "-{2}";
            }
            else
            {
                nameOfGifForOutputCompositeGif = "{0}-TEMP-TEST-COMPOSITE-OBFUSCATE-OUTPUT-{1}-" + strGuid + "-{2}";
            }
            string pathCompositeImageOutPreRotate  = Path.Combine(pathToTemp, String.Format(nameOfGifForOutputCompositeGif, iso, "A-PRE-ROTATE", TESTIMAGE_OBFUSCATED));
            string pathCompositeImageOutPostRotate = Path.Combine(pathToTemp, String.Format(nameOfGifForOutputCompositeGif, iso, "B-PST-ROTATE", TESTIMAGE_OBFUSCATED));

            ql(String.Format("Starting deObfuscateImage - about to start writing multiple tiles to a single file. Tile width : {0} and tile height : {1}.", SMALLTILEWIDTH, SMALLTILEHEIGHT));
            using (var image = new MagickImage(pathOfInputGif))
            {
                if (obfMode == ObfuscationMode.OBFUSCATE)
                {
                    image.Rotate(180);
                }
                int tilesHigh = image.Height / SMALLTILEHEIGHT;
                int tilesWide = image.Width / SMALLTILEWIDTH;
                int tileIndex = 0;

                //The 'Blue' background is just to highlight any problems with tile layout
                var imageout = new MagickImage(MagickColors.Blue, image.Width, image.Height);

                //Two steps to the List because I couldn't figure out a better way to do it !
                IEnumerable <IMagickImage <byte> > enumerableTiles = image.CropToTiles(SMALLTILEWIDTH, SMALLTILEHEIGHT);
                List <IMagickImage <byte> >        lstTiles        = enumerableTiles.ToList <IMagickImage <byte> >();
                //
                for (int ystepper = 0; ystepper < tilesHigh; ystepper++)
                {
                    pixelYDestination = ystepper * SMALLTILEHEIGHT;
                    for (int xstepper = 0; xstepper < tilesWide; xstepper++)
                    {
                        if ((ystepper % 2) == 0)
                        {
                            pixelXDestination = xstepper * SMALLTILEWIDTH;
                        }
                        else
                        {
                            pixelXDestination = ((((image.Width / SMALLTILEWIDTH) - 1) - xstepper) * SMALLTILEWIDTH);
                        }
                        //'Paste' the current tile onto the output image at the X/Y determined above
                        imageout.Composite(lstTiles[tileIndex], pixelXDestination, pixelYDestination);
                        ql(String.Format("Writing tile {0} at location ({1}, {2})", tileIndex, pixelXDestination, pixelYDestination));
                        tileIndex++;
                    }
                }

                imageout.Write(pathCompositeImageOutPreRotate);

                if (obfMode == ObfuscationMode.DEOBFUSCATE)
                {
                    imageout.Rotate(180);
                }
                imageout.Write(pathCompositeImageOutPostRotate);
            }
            //return Path.GetFileName(pathCompositeImageOutPostRotate).ToString();
            return(pathCompositeImageOutPostRotate);
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            Console.WriteLine($"# of Threads: {NumThreads}");

            DateTime startTime = DateTime.Now;

            MagickImage original = new MagickImage("sample_images/white.png");

            MagickImage target = new MagickImage("sample_images/target.png");

            List <MagickImage> originalTiles = original.CropToTiles((original.Width / NumThreads) + 1, original.Height).Cast <MagickImage>().ToList();
            List <MagickImage> targetTiles   = target.CropToTiles((original.Width / NumThreads) + 1, original.Height).Cast <MagickImage>().ToList();

            List <MagickImage>[] outputTilesProcessed = new List <MagickImage> [NumThreads];

            //MagickImage working = (MagickImage)original.Clone(original.Width, original.Height);

            Console.WriteLine($"ogT cnt: {originalTiles.Count}, tt cnt: {targetTiles.Count}");

            List <Thread> threads = new List <Thread>();

            DateTime threadStartTime = DateTime.Now;

            for (int i = 0; i < NumThreads; i++)
            {
                int    i_copied = i;
                Thread t        = new Thread(delegate()
                {
                    outputTilesProcessed[i_copied] = ProcessTile(originalTiles[i_copied], targetTiles[i_copied]);
                });

                t.Start();

                threads.Add(t);
            }

            while (!threads.All(t => !t.IsAlive))
            {
                Thread.Sleep(1);
            }

            Console.WriteLine($"Tile process time: {Math.Round((DateTime.Now - threadStartTime).TotalSeconds, 2)} seconds");

            DateTime stitchStartTime = DateTime.Now;

            using (MagickImageCollection gifCollection = new MagickImageCollection())
            {
                for (int i = 0; i < num_frames; i++)
                {
                    using (MagickImageCollection frameCollection = new MagickImageCollection())
                    {
                        for (int j = 0; j < NumThreads; j++)
                        {
                            frameCollection.Add(outputTilesProcessed[j][i]);
                        }

                        gifCollection.Add(frameCollection.AppendHorizontally());

                        gifCollection[i].AnimationDelay = animation_delay;
                    }
                }

                Console.WriteLine($"Stitch time: {Math.Round((DateTime.Now - stitchStartTime).TotalSeconds, 2)} seconds");

                DateTime optimizeWriteStartTime = DateTime.Now;

                gifCollection.Optimize();
                gifCollection.Write("output/output.gif");

                Console.WriteLine($"Optimize and write time: {Math.Round((DateTime.Now - optimizeWriteStartTime).TotalSeconds, 2)} seconds");
            }

            Console.WriteLine($"Done, total elapsed time: {Math.Round((DateTime.Now - startTime).TotalSeconds, 2)} seconds");

            //Gif animation = new Gif("output/output.gif", num_frames);

            /*using (MagickImageCollection collection = new MagickImageCollection())
             * {
             *  collection.Add(working);
             *  collection[0].AnimationDelay = animation_delay;
             *
             *  //collection[0].Write("output/0.png");
             *
             *  for (int i = 1; i < num_frames; i++)
             *  {
             *      DateTime startFrameTime = DateTime.Now;
             *      collection.Add(Method2_Magick((MagickImage)collection[i-1], target));
             *
             *      collection[i].AnimationDelay = animation_delay;
             *
             *      DateTime endFrameTime = DateTime.Now;
             *
             *      Console.WriteLine($"Frame {i}/{num_frames-1} took {Math.Round((endFrameTime - startFrameTime).TotalSeconds, 2)} seconds to render");
             *
             *      //Console.WriteLine($"{i}/{num_frames-1}");
             *
             *
             *      //collection[i].Write($"output/{i}.png");
             *
             *      //working.Save($"output/{(char)i}.png");
             *  }
             *
             *  DateTime startOptimizeAndSave = DateTime.Now;
             *
             *  collection.Optimize();
             *
             *  collection.Write("output/output.gif");
             *
             *  DateTime endOptimizeAndSave = DateTime.Now;
             *
             *  Console.WriteLine($"Optimize + save took {Math.Round((endOptimizeAndSave-startOptimizeAndSave).TotalSeconds, 2)} seconds");
             * }
             *
             * DateTime endTime = DateTime.Now;
             *
             * Console.WriteLine($"Done, total elapsed time: {Math.Round((endTime-startTime).TotalSeconds, 2)} seconds");*/
        }
Exemplo n.º 12
0
        public async Task <string> StartProcessing(InstructionSet instructions)
        {
            string validationResult = Validate(instructions);

            if (validationResult != null)
            {
                return(validationResult);
            }

            Size?dims = ImageHelper.GetDimensions(instructions.InputPath);

            if (dims == null)
            {
                return(null);
            }

            string      inputPath       = instructions.InputPath;
            int         minZoom         = instructions.MinimumZoom;
            int         maxZoom         = instructions.MaximumZoom;
            string      outputDirectory = instructions.OutputDirectory;
            string      baseName        = instructions.OutputName;
            ImageFormat outputFormat    = instructions.OutputFormat;
            string      outputExtension = outputFormat.GetFileExtension();
            int         outputSize      = instructions.OutputSize;

            return(await Task <string> .Run(() =>
            {
                try
                {
                    int processed = 0;
                    for (int zoom = minZoom; zoom <= maxZoom; zoom++)
                    {
                        if (ProgressChanged != null)
                        {
                            ProgressChanged(this, new ProgressChangedEventArgs(processed, "Processing zoom " + zoom));
                        }

                        int tiles = 1 << zoom;


                        var input = new MagickImage(inputPath);

                        input.Resize(outputSize *tiles, outputSize *tiles);

                        var x = -1;
                        var y = 0;
                        foreach (var tile in input.CropToTiles(outputSize, outputSize))
                        {
                            x++;
                            y += x / tiles;
                            x %= tiles;

                            var outPath = Path.Combine(outputDirectory,
                                                       string.Format("{0}.{1}.{2}.{3}{4}", baseName, zoom, x, y, outputExtension));

                            if (!instructions.SkipExisting || !File.Exists(outPath))
                            {
                                tile.Write(outPath);
                            }

                            if (ProgressChanged != null)
                            {
                                ProgressChanged(this,
                                                new ProgressChangedEventArgs(++processed, "Processing zoom " + zoom));
                            }
                        }


//                        RunMagick(string.Format(
//                            "\"{6}\" -resize {0}x{0} -crop {1}x{1} -set filename:tile \"%[fx:page.x/{1}].%[fx:page.y/{1}]\" " +
//                            "+repage +adjoin \"{2}/{3}.{4}.%[filename:tile]{5}\"", outputSize * tiles, outputSize,
//                            outputDirectory, baseName, zoom, outputExtension, inputPath));
                    }
                }
                catch (Exception e)
                {
                    return e.Message;
                }

                return null;
            }));
        }