Example #1
0
        static void Draw(dynamic map, WDT.WDTFileDataId chunk, ref NetVips.Image canvas, int positionX, int positionY)
        {
            Stream chunkStream = null;

            try
            {
                var casc = new CASC();
                chunkStream = casc.File(BuildConfig, chunk.fileDataId);
            }
            catch
            {
                Console.WriteLine($"Failed to download chunk {chunk.x}_{chunk.y} for map {map.MapName_lang} ({map.ID})");
                return;
            }

            var blpStream = new MemoryStream();
            var blpFile   = new BlpFile(chunkStream);

            var bitmap = blpFile.GetBitmap(0);

            bitmap.Save(blpStream, System.Drawing.Imaging.ImageFormat.Png);

            var image = NetVips.Image.NewFromBuffer(blpStream.ToArray(), access: Enums.Access.Sequential);

            canvas = canvas.Insert(image, positionX * bitmap.Width, positionY * bitmap.Height, true);

            blpStream.Dispose();
            blpFile.Dispose();
            bitmap.Dispose();
            image.Dispose();;
        }
Example #2
0
        /// <summary>
        /// Creates new <see cref="Raster"/> object.
        /// </summary>
        /// <param name="inputFileInfo">Input GeoTiff image.</param>
        public Raster(FileInfo inputFileInfo)
        {
            //Disable NetVips warnings for tiff.
            NetVipsHelper.DisableLog();

            #region Check parameters

            CheckHelper.CheckFile(inputFileInfo, true);

            #endregion

            Data = NetVips.Image.NewFromFile(inputFileInfo.FullName, access: NetVips.Enums.Access.Random);

            //Get border coordinates и raster sizes.
            try
            {
                RasterXSize = Data.Width;
                RasterYSize = Data.Height;
                (MinX, MinY, MaxX, MaxY) = Gdal.Gdal.GetImageBorders(inputFileInfo, RasterXSize, RasterYSize);
            }
            catch (Exception exception)
            {
                throw new RasterException(string.Format(Strings.UnableToGetCoordinates, nameof(inputFileInfo),
                                                        exception));
            }
        }
Example #3
0
        /* Area map*/
        static public void Make_AreaMap(string base_dir, Dictionary <int, List <Toolbox.Area> > Areas, Wdt wdt)
        {
            Console.WriteLine("Making area map:");
            string area_fullmap  = base_dir + "/map_areas.png";
            var    tilesize      = 256;
            int    size_per_mcnk = tilesize / 16;
            string areasjson     = "[";
            List <System.Drawing.Color> colors = new List <System.Drawing.Color>();

            using (var areaall = new System.Drawing.Bitmap(wdt.size_y * tilesize, wdt.size_x * tilesize)) {
                using (var area_graphics = System.Drawing.Graphics.FromImage(areaall)) {
                    areaall.MakeTransparent();
                    area_graphics.DrawImage(areaall, 0, 0, areaall.Width, areaall.Height);
                    foreach (KeyValuePair <int, List <Toolbox.Area> > area in Areas)
                    {
                        Random rnd       = new Random();
                        var    AreaColor = System.Drawing.Color.FromArgb(255 / 2, rnd.Next(255), rnd.Next(255), rnd.Next(255));
                        while (colors.Contains(AreaColor))
                        {
                            AreaColor = System.Drawing.Color.FromArgb(255 / 2, rnd.Next(255), rnd.Next(255), rnd.Next(255));
                        }
                        colors.Add(AreaColor);
                        if (areasjson != "[")
                        {
                            areasjson += ",";
                        }
                        //Console.WriteLine(AreaColor.R + " / " + AreaColor.G + " /  " + AreaColor.B);
                        areasjson += "{\"r\":" + (Math.Round(AreaColor.R * (1.0f - (64.0f / 127f)))) + ",\"g\":" + (Math.Round(AreaColor.G * (1.0f - (64.0f / 127f)))) + ",\"b\":" + (Math.Round(AreaColor.B * (1.0f - (64.0f / 127f)))) + ",\"ID\":\"" + area.Value[0].ID + "\",\"ZoneName\":\"" + area.Value[0].ZoneName + "\",\"ContinentID\":" + area.Value[0].ContinentID + ",\"AreaName_lang\":\"" + area.Value[0].AreaName_lang + "\"}";
                        using (System.Drawing.SolidBrush AreaBrush = new System.Drawing.SolidBrush(AreaColor)) {
                            foreach (Toolbox.Area a in area.Value)
                            {
                                area_graphics.FillRectangle(AreaBrush, ((a.y - wdt.min_y) * tilesize) + (a.sub_x * size_per_mcnk), ((a.x - wdt.min_x) * tilesize) + (a.sub_y * size_per_mcnk), size_per_mcnk, size_per_mcnk);
                            }
                        }
                    }
                }
                Console.WriteLine("writing area map");
                NetVips.Image netimg = BitmapConverter.ToVips(areaall);
                netimg = netimg.Resize(2, "VIPS_KERNEL_NEAREST");
                netimg.WriteToFile(area_fullmap);
            }
            CutMap(area_fullmap, base_dir + "/area_tiles", 10);
            areasjson += "]";
            File.WriteAllText(base_dir + "/areas.json", areasjson);
        }
Example #4
0
        /* Unknown map */
        static public void Make_UnknownMap(string base_dir, Adt[,] adts, Wdt wdt)
        {
            Console.WriteLine("Making unknown map:");
            string unknown_fullmap = base_dir + "/map_unknown.png";
            var    tilesize        = 256;
            int    size_per_mcnk   = tilesize / 16;

            System.Drawing.SolidBrush unknown_brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(170, 255, 255, 255));
            using (var areaall = new System.Drawing.Bitmap(wdt.size_y * tilesize, wdt.size_x * tilesize)) {
                using (var area_graphics = System.Drawing.Graphics.FromImage(areaall)) {
                    /*areaall.MakeTransparent();
                     * area_graphics.DrawImage(areaall, 0, 0, areaall.Width, areaall.Height);*/
                    for (int x = 0; x < 64; x++)
                    {
                        for (int y = 0; y < 64; y++)
                        {
                            for (int sub_x = 0; sub_x < 16; sub_x++)
                            {
                                for (int sub_y = 0; sub_y < 16; sub_y++)
                                {
                                    if (adts[x, y].unknown[sub_x, sub_y] == 1)
                                    {
                                        area_graphics.FillRectangle(unknown_brush, ((y - wdt.min_y) * tilesize) + (sub_x * size_per_mcnk), ((x - wdt.min_x) * tilesize) + (sub_y * size_per_mcnk), size_per_mcnk, size_per_mcnk);
                                    }
                                }
                            }
                        }
                    }
                }
                unknown_brush.Dispose();
                Console.WriteLine("writing unknown map");
                NetVips.Image netimg = BitmapConverter.ToVips(areaall);
                netimg = netimg.Resize(2, "VIPS_KERNEL_NEAREST");
                netimg.WriteToFile(unknown_fullmap);
            }
            CutMap(unknown_fullmap, base_dir + "/unknown_tiles", 10);
        }
Example #5
0
        /// <summary>
        /// Writes new tile by joining 4 lower ones.
        /// </summary>
        /// <param name="zoom">Current zoom level.</param>
        /// <param name="tileX">Tile's x number.</param>
        /// <param name="tileY">Tile's y number.</param>
        private void WriteTile(int zoom, int tileX, int tileY)
        {
            #region Parameters checking

            if (zoom < 0)
            {
                throw new ImageException(string.Format(Strings.LesserThan, nameof(zoom), 0));
            }
            if (tileX < 0)
            {
                throw new ImageException(string.Format(Strings.LesserThan, nameof(tileX), 0));
            }
            if (tileY < 0)
            {
                throw new ImageException(string.Format(Strings.LesserThan, nameof(tileY), 0));
            }

            #endregion

            //Create directories for the tile. The overall structure looks like: outputDirectory/zoom/x/y.png.
            DirectoryInfo tileDirectoryInfo = new DirectoryInfo(Path.Combine(OutputDirectoryInfo.FullName,
                                                                             $"{zoom}", $"{tileX}"));
            CheckHelper.CheckDirectory(tileDirectoryInfo);

            //Warning: OpenLayers requires replacement of tileY to tileY+1

            //Calculate upper tiles's positions.
            int upperTileX1 = tileX * 2;
            int upperTileY1 = tileY * 2;
            int upperTileX2 = upperTileX1 + 1;
            int upperTileY2 = upperTileY1;
            int upperTileX3 = upperTileX1;
            int upperTileY3 = upperTileY1 + 1;
            int upperTileX4 = upperTileX1 + 1;
            int upperTileY4 = upperTileY1 + 1;

            bool tilesExists = false;

            const int upperTileSize = Enums.Image.Image.TileSize / 2;

            #region Create 4 inner tiles

            NetVips.Image upperTileImage1;
            string        tile1Path = Path.Combine(OutputDirectoryInfo.FullName, $"{zoom + 1}", $"{upperTileX1}",
                                                   $"{upperTileY1}{Enums.Extensions.Png}");

            try
            {
                if (File.Exists(tile1Path))
                {
                    upperTileImage1 = NetVips.Image.Pngload(tile1Path);
                    upperTileImage1 = upperTileImage1.ThumbnailImage(upperTileSize, upperTileSize);
                    tilesExists     = true;
                }
                else
                {
                    upperTileImage1 = NetVips.Image.Black(upperTileSize, upperTileSize);
                }
            }
            catch (Exception exception)
            {
                throw new ImageException(string.Format(Strings.UnableToCreateTile, tileX, tileY), exception);
            }

            NetVips.Image upperTileImage2;
            string        tile2Path = Path.Combine(OutputDirectoryInfo.FullName, $"{zoom + 1}", $"{upperTileX2}",
                                                   $"{upperTileY2}{Enums.Extensions.Png}");

            try
            {
                if (File.Exists(tile2Path))
                {
                    upperTileImage2 = NetVips.Image.Pngload(tile2Path);
                    upperTileImage2 = upperTileImage2.ThumbnailImage(upperTileSize, upperTileSize);
                    tilesExists     = true;
                }
                else
                {
                    upperTileImage2 = NetVips.Image.Black(upperTileSize, upperTileSize);
                }
            }
            catch (Exception exception)
            {
                throw new ImageException(string.Format(Strings.UnableToCreateTile, tileX, tileY), exception);
            }

            NetVips.Image upperTileImage3;
            string        tile3Path = Path.Combine(OutputDirectoryInfo.FullName, $"{zoom + 1}", $"{upperTileX3}",
                                                   $"{upperTileY3}{Enums.Extensions.Png}");

            try
            {
                if (File.Exists(tile3Path))
                {
                    upperTileImage3 = NetVips.Image.Pngload(tile3Path);
                    upperTileImage3 = upperTileImage3.ThumbnailImage(upperTileSize, upperTileSize);
                    tilesExists     = true;
                }
                else
                {
                    upperTileImage3 = NetVips.Image.Black(upperTileSize, upperTileSize);
                }
            }
            catch (Exception exception)
            {
                throw new ImageException(string.Format(Strings.UnableToCreateTile, tileX, tileY), exception);
            }

            NetVips.Image upperTileImage4;
            string        tile4Path = Path.Combine(OutputDirectoryInfo.FullName, $"{zoom + 1}", $"{upperTileX4}",
                                                   $"{upperTileY4}{Enums.Extensions.Png}");

            try
            {
                if (File.Exists(tile4Path))
                {
                    upperTileImage4 = NetVips.Image.Pngload(tile4Path);
                    upperTileImage4 = upperTileImage4.ThumbnailImage(upperTileSize, upperTileSize);
                    tilesExists     = true;
                }
                else
                {
                    upperTileImage4 = NetVips.Image.Black(upperTileSize, upperTileSize);
                }
            }
            catch (Exception exception)
            {
                throw new ImageException(string.Format(Strings.UnableToCreateTile, tileX, tileY), exception);
            }

            #endregion

            //We shouldn't create tiles, if they're not exist.
            if (!tilesExists)
            {
                return;
            }

            NetVips.Image[] images = { upperTileImage3, upperTileImage4, upperTileImage1, upperTileImage2 };

            //Check and write bands if needed.
            for (int imagesIndex = 0; imagesIndex < images.Length; imagesIndex++)
            {
                int bands = images[imagesIndex].Bands;

                //Check number before switching on it.
                if (bands > Enums.Image.Image.Bands)
                {
                    throw new ImageException(string.Format(Strings.TooMuchBands));
                }

                switch (bands)
                {
                case Enums.Image.Image.Bands:
                    continue;

                case 1:
                {
                    for (int bandsIndex = bands; bandsIndex < Enums.Image.Image.Bands; bandsIndex++)
                    {
                        try
                        {
                            images[imagesIndex] = images[imagesIndex].Bandjoin(0);
                        }
                        catch (Exception exception)
                        {
                            throw new ImageException(string.Format(Strings.UnableToJoin, $"band {bandsIndex}",
                                                                   tileX, tileY), exception);
                        }
                    }
                    break;
                }

                default:
                {
                    for (int bandsIndex = bands; bandsIndex < Enums.Image.Image.Bands; bandsIndex++)
                    {
                        try
                        {
                            images[imagesIndex] = images[imagesIndex].Bandjoin(255);
                        }
                        catch (Exception exception)
                        {
                            throw new ImageException(string.Format(Strings.UnableToJoin, $"band {bandsIndex}",
                                                                   tileX, tileY), exception);
                        }
                    }
                    break;
                }
                }
            }

            //Join 4 tiles.
            FileInfo outputTileFileInfo = new FileInfo(Path.Combine(tileDirectoryInfo.FullName,
                                                                    $"{tileY}{Enums.Extensions.Png}"));
            try
            {
                using (NetVips.Image resultImage = NetVips.Image.Arrayjoin(images, 2))
                {
                    resultImage.Pngsave(outputTileFileInfo.FullName);
                }
            }
            catch (Exception exception)
            {
                throw new ImageException(string.Format(Strings.UnableToJoin, nameof(outputTileFileInfo),
                                                       tileX, tileY), exception);
            }

            CheckHelper.CheckFile(outputTileFileInfo, true);

            //Dispose images.
            upperTileImage1.Dispose();
            upperTileImage2.Dispose();
            upperTileImage3.Dispose();
            upperTileImage4.Dispose();
            foreach (NetVips.Image image in images)
            {
                image.Dispose();
            }
        }
Example #6
0
        /// <summary>
        /// Writes one tile of current zoom.
        /// <para/>Crops zoom directly from input image.
        /// </summary>
        /// <param name="zoom">Zoom level.</param>
        /// <param name="tileX">Tile x.</param>
        /// <param name="tileY">Tile y.</param>
        /// <param name="inputImage">Input image.</param>
        private void WriteTile(int zoom, int tileX, int tileY, NetVips.Image inputImage)
        {
            #region Parameters checking

            if (zoom < 0)
            {
                throw new ImageException(string.Format(Strings.LesserThan, nameof(zoom), 0));
            }
            if (tileX < 0)
            {
                throw new ImageException(string.Format(Strings.LesserThan, nameof(tileX), 0));
            }
            if (tileY < 0)
            {
                throw new ImageException(string.Format(Strings.LesserThan, nameof(tileY), 0));
            }

            #endregion

            //Create directories for the tile. The overall structure looks like: outputDirectory/zoom/x/y.png.
            DirectoryInfo tileDirectoryInfo = new DirectoryInfo(Path.Combine(OutputDirectoryInfo.FullName,
                                                                             $"{zoom}", $"{tileX}"));
            CheckHelper.CheckDirectory(tileDirectoryInfo);

            const bool centreConvention = false;

            //Get the coordinate borders for current tile from tile numbers.
            (double minX, double minY, double maxX, double maxY) = Tile.Tile.TileBounds(tileX, tileY, zoom, TmsCompatible);

            //Get postitions and sizes for current tile.
            (int readPosX, int readPosY, int readXSize, int readYSize, int writePosX, int writePosY,
             int writeXSize, int writeYSize) = GeoQuery(minX, maxY, maxX, minY);

            //Warning: OpenLayers requires replacement of tileY to tileY+1
            FileInfo outputTileFileInfo = new FileInfo(Path.Combine(tileDirectoryInfo.FullName,
                                                                    $"{tileY}{Enums.Extensions.Png}"));

            //Try open input image and crop tile
            NetVips.Image tileImage;
            try
            {
                tileImage = inputImage.Crop(readPosX, readPosY, readXSize, readYSize);
            }
            catch (Exception exception)
            {
                throw new ImageException(string.Format(Strings.UnableToCreateTile, tileX, tileY), exception);
            }

            // Scaling calculations
            double xScale = 1.0 / ((double)tileImage.Width / writeXSize);
            double yScale = 1.0 / ((double)tileImage.Height / writeYSize);

            // Calculate integral box shrink
            // We will get the best quality (but be the slowest) if we let reduce
            // do all the work. Leave it the final 200 - 300% to do as a compromise
            // for efficiency.
            int xShrink = Math.Max(1, (int)Math.Floor(1.0 / (xScale * 2.0)));
            int yShrink = Math.Max(1, (int)Math.Floor(1.0 / (yScale * 2.0)));

            // Fast, integral box-shrink
            if (yShrink > 1)
            {
                tileImage = tileImage.Shrinkv(yShrink);
                yScale   *= yShrink;
            }
            if (xShrink > 1)
            {
                tileImage = tileImage.Shrinkh(xShrink);
                xScale   *= xShrink;
            }

            // Any residual downsizing
            if (yScale < 1.0)
            {
                tileImage = tileImage.Reducev(1.0 / yScale, NetVips.Enums.Kernel.Lanczos3, centreConvention);
            }
            if (xScale < 1.0)
            {
                tileImage = tileImage.Reduceh(1.0 / xScale, NetVips.Enums.Kernel.Lanczos3, centreConvention);
            }

            // Any upsizing
            if (xScale > 1.0 || yScale > 1.0)
            {
                // Input displacement. For centre sampling, shift by 0.5 down and right.
                //double id = centreConvention ? 0.5 : 0.0;
                const double id = 0.0;

                // Floating point affine transformation
                using (Interpolate interpolate = Interpolate.NewFromName(Enums.Image.Interpolations.Bicubic))
                {
                    if (xScale > 1.0 && yScale > 1.0)
                    {
                        tileImage = tileImage.Affine(new[] { xScale, 0.0, 0.0, yScale }, interpolate, idx: id, idy: id,
                                                     extend: NetVips.Enums.Extend.Copy);
                    }
                    else if (xScale > 1.0)
                    {
                        tileImage = tileImage.Affine(new[] { xScale, 0.0, 0.0, 1.0 }, interpolate, idx: id, idy: id,
                                                     extend: NetVips.Enums.Extend.Copy);
                    }
                    else
                    {
                        tileImage = tileImage.Affine(new[] { 1.0, 0.0, 0.0, yScale }, interpolate, idx: id, idy: id,
                                                     extend: NetVips.Enums.Extend.Copy);
                    }
                }
            }

            // Add alpha channel if needed
            for (; tileImage.Bands < Enums.Image.Image.Bands;)
            {
                tileImage = tileImage.Bandjoin(255);
            }

            // Make a transparent image
            NetVips.Image outputImage;
            try
            {
                outputImage = NetVips.Image.Black(Enums.Image.Image.TileSize, Enums.Image.Image.TileSize)
                              .NewFromImage(0, 0, 0, 0);

                // Insert tile into output image
                outputImage = outputImage.Insert(tileImage, writePosX, writePosY);
                outputImage.Pngsave(outputTileFileInfo.FullName);
            }
            catch (Exception exception)
            {
                throw new ImageException(string.Format(Strings.UnableToCreateTile, tileX, tileY), exception);
            }

            //Check if tile was created successfuly.
            CheckHelper.CheckFile(outputTileFileInfo, true);

            tileImage.Dispose();
            outputImage.Dispose();
        }
Example #7
0
        /* Impass map */
        static public void Make_ImpassMap(string base_dir, Adt[,] adts, Wdt wdt)
        {
            Console.WriteLine("Making impass map:");
            string impass_fullmap = base_dir + "/map_impass.png";
            var    tilesize       = 256;
            int    size_per_mcnk  = tilesize / 16;
            Pen    impass_pen     = new Pen(Color.FromArgb(220, 255, 255, 0), 2.5f);
            Pen    mid_impass_pen = new Pen(Color.FromArgb(220, 255, 0, 0), 2.5f);

            //Console.WriteLine(wdt.size_x + " / "+  wdt.size_y);

            using (var bitmap = new System.Drawing.Bitmap(wdt.size_y * tilesize, wdt.size_x * tilesize)) {
                using (var g_impass = System.Drawing.Graphics.FromImage(bitmap)) {
                    bitmap.MakeTransparent();
                    g_impass.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
                    for (int a = 0; a < 64; a++)
                    {
                        for (int b = 0; b < 64; b++)
                        {
                            for (int i = 0; i < 16; i++)
                            {
                                for (int j = 0; j < 16; j++)
                                {
                                    Point topright    = new Point((b - wdt.min_y) * tilesize + (int)size_per_mcnk * (int)i, (a - wdt.min_x) * tilesize + (int)size_per_mcnk * ((int)j + 1));
                                    Point topleft     = new Point((b - wdt.min_y) * tilesize + (int)size_per_mcnk * (int)i, (a - wdt.min_x) * tilesize + (int)size_per_mcnk * (int)j);
                                    Point bottomright = new Point((b - wdt.min_y) * tilesize + (int)size_per_mcnk * ((int)i + 1), (a - wdt.min_x) * tilesize + (int)size_per_mcnk * ((int)j + 1));
                                    Point botttomleft = new Point((b - wdt.min_y) * tilesize + (int)size_per_mcnk * ((int)i + 1), (a - wdt.min_x) * tilesize + (int)size_per_mcnk * (int)j);

                                    int up      = 0;
                                    int down    = 0;
                                    int left    = 0;
                                    int right   = 0;
                                    int current = adts[a, b].impasses[i, j];

                                    if (j > 0)
                                    {
                                        left = adts[a, b].impasses[i, j - 1];
                                    }
                                    else if (a > 0)
                                    {
                                        left = adts[a - 1, b].impasses[i, 15];
                                    }
                                    else
                                    {
                                        left = -1; // wall
                                    }
                                    if (j < 15)
                                    {
                                        right = adts[a, b].impasses[i, j + 1];
                                    }
                                    else if (a < 63)
                                    {
                                        right = adts[a + 1, b].impasses[i, 0];
                                    }
                                    else
                                    {
                                        right = -1; // wall
                                    }
                                    if (i > 0)
                                    {
                                        up = adts[a, b].impasses[i - 1, j];
                                    }
                                    else if (b > 0)
                                    {
                                        up = adts[a, b - 1].impasses[15, j];
                                    }
                                    else
                                    {
                                        up = -1; // wall
                                    }
                                    if (i < 15)
                                    {
                                        down = adts[a, b].impasses[i + 1, j];
                                    }
                                    else if (b < 63)
                                    {
                                        down = adts[a, b + 1].impasses[0, j];
                                    }
                                    else
                                    {
                                        down = -1; // wall
                                    }
                                    if (current == 1)
                                    {
                                        if (left == 1)
                                        {
                                            g_impass.DrawLine(mid_impass_pen, topleft, botttomleft);
                                        }
                                        else if (left == -1)
                                        {
                                            g_impass.DrawLine(impass_pen, topleft, botttomleft);
                                        }
                                        if (right == 1)
                                        {
                                            g_impass.DrawLine(mid_impass_pen, topright, bottomright);
                                        }
                                        else if (right == -1)
                                        {
                                            g_impass.DrawLine(impass_pen, topright, bottomright);
                                        }
                                        if (up == 1)
                                        {
                                            g_impass.DrawLine(mid_impass_pen, topleft, topright);
                                        }
                                        else if (up == -1)
                                        {
                                            g_impass.DrawLine(impass_pen, topleft, topright);
                                        }
                                        if (down == 1)
                                        {
                                            g_impass.DrawLine(mid_impass_pen, botttomleft, bottomright);
                                        }
                                        else if (down == -1)
                                        {
                                            g_impass.DrawLine(impass_pen, botttomleft, bottomright);
                                        }
                                    }
                                    else if (current == 0)
                                    {
                                        if (left == 1)
                                        {
                                            g_impass.DrawLine(mid_impass_pen, topleft, botttomleft);
                                        }
                                        if (right == 1)
                                        {
                                            g_impass.DrawLine(mid_impass_pen, topright, bottomright);
                                        }
                                        if (up == 1)
                                        {
                                            g_impass.DrawLine(mid_impass_pen, topleft, topright);
                                        }
                                        if (down == 1)
                                        {
                                            g_impass.DrawLine(mid_impass_pen, botttomleft, bottomright);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                impass_pen.Dispose();
                mid_impass_pen.Dispose();
                Console.WriteLine("writing impass map");
                NetVips.Image netimg = BitmapConverter.ToVips(bitmap);
                netimg = netimg.Resize(2, "VIPS_KERNEL_NEAREST");
                netimg.WriteToFile(impass_fullmap);
            }
            CutMap(impass_fullmap, base_dir + "/impass_tiles", 10);
        }
Example #8
0
        private void LoadImages(string imagePath, int thumbnailSize)
        {
            using (var context = new NopCommerceDbContext())
            {
                var directories = Directory.GetDirectories(imagePath);
                foreach (var directory in directories)
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(directory);

                    var siteProducts = context.Products.Where(p => p.ManufacturerPartNumber == directoryInfo.Name).ToList();

                    foreach (var siteProduct in siteProducts)
                    {
                        Log = siteProduct.Name + "\r\n" + Log;

                        if (siteProduct != null)
                        {
                            var productPictures = siteProduct.Product_Picture_Mapping;
                            foreach (var productPicture in productPictures.ToList())
                            {
                                var binaries = context.PictureBinaries.Where(pb => pb.PictureId == productPicture.PictureId);
                                foreach (var binary in binaries)
                                {
                                    context.PictureBinaries.Remove(binary);
                                }

                                context.Pictures.Remove(productPicture.Picture);
                            }

                            productPictures.Clear();

                            var files = directoryInfo.GetFiles("*.*");

                            foreach (var file in files)
                            {
                                if (file.Extension.ToLower() == ".png" || file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".jpeg")
                                {
                                    var fileExtension = file.Extension.ToLower();
                                    if (fileExtension == ".jpeg")
                                    {
                                        fileExtension = ".jpg";
                                    }

                                    NetVips.Image smallerImage = NetVips.Image.Thumbnail(file.FullName, thumbnailSize);

                                    var picture = new Picture()
                                    {
                                        MimeType = $"image/{fileExtension.Replace(".", "")}"
                                    };
                                    context.Pictures.Add(picture);
                                    context.SaveChanges();

                                    var data = new PictureBinary()
                                    {
                                        PictureId  = picture.Id,
                                        BinaryData = smallerImage.WriteToBuffer($"{fileExtension}")
                                    };
                                    context.PictureBinaries.Add(data);

                                    siteProduct.Product_Picture_Mapping.Add(new Product_Picture_Mapping()
                                    {
                                        PictureId = picture.Id
                                    });
                                }
                            }

                            context.SaveChanges();
                        }
                    }
                }
            }
        }