public FormPreRenderTiles(TileServiceMetadata metadata, MapServerClass mapServerClass)
        {
            _metadata       = metadata;
            _mapServerClass = mapServerClass;

            InitializeComponent();

            if (_metadata != null)
            {
                foreach (int epsg in _metadata.EPSGCodes)
                {
                    cmbEpsg.Items.Add(epsg);
                }
                if (cmbEpsg.Items.Count > 0)
                {
                    cmbEpsg.SelectedIndex = 0;
                }
            }

            if (_mapServerClass != null && _mapServerClass.Dataset != null)
            {
                txtServer.Text  = ConfigTextStream.ExtractValue(_mapServerClass.Dataset.ConnectionString, "server");
                txtService.Text = ConfigTextStream.ExtractValue(_mapServerClass.Dataset.ConnectionString, "service");
            }

            numMaxParallelRequest.Value = _maxParallelRequests;

            if (metadata.FormatPng)
            {
                cmbImageFormat.Items.Add("image/png");
            }
            if (metadata.FormatJpg)
            {
                cmbImageFormat.Items.Add("image/jpeg");
            }

            if (metadata.UpperLeft && metadata.UpperLeftCacheTiles)
            {
                cmbOrigin.Items.Add("Upper Left");
            }
            if (metadata.LowerLeft && metadata.LowerLeftCacheTiles)
            {
                cmbOrigin.Items.Add("Lower Left");
            }

            if (cmbImageFormat.Items.Count > 0)
            {
                cmbImageFormat.SelectedIndex = 0;
            }
            if (cmbOrigin.Items.Count > 0)
            {
                cmbOrigin.SelectedIndex = 0;
            }

            if (cmbCacheFormat.Items.Count > 0)
            {
                cmbCacheFormat.SelectedIndex = 0;
            }
        }
Beispiel #2
0
        private void WmtsMetadata100(IServiceRequestContext context, TileServiceMetadata metadata)
        {
            XmlStream stream = new XmlStream("WmtsMetadata");

            stream.Save("TileServiceMetadata", metadata);

            context.ServiceRequest.Response            = stream.ToString();
            context.ServiceRequest.ResponseContentType = "text/xml";
        }
Beispiel #3
0
 private double GetScale(TileServiceMetadata metadata, string scaleArgument)
 {
     if (scaleArgument.StartsWith("~"))
     {
         scaleArgument = scaleArgument.Substring(1);
         return(metadata.Scales[int.Parse(scaleArgument)]);
     }
     return(double.Parse(scaleArgument.Replace(",", "."), _nhi));
 }
Beispiel #4
0
        async private Task <byte[]> GetTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            //if (!metadata.Scales.Contains(scale))
            //    throw new ArgumentException("Wrong scale argument");
            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEPSGEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }

            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }

            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"/" + MapName(context) + @"/_alllayers/" +
                          TileServiceMetadata.TilePath(orientation, epsg, scale, row, col) + format;

            if ((orientation == GridOrientation.UpperLeft && metadata.UpperLeftCacheTiles) ||
                (orientation == GridOrientation.LowerLeft && metadata.LowerLeftCacheTiles))
            {
                FileInfo fi = new FileInfo(path);
                if (fi.Exists)
                {
                    //context.ServiceRequest.Response = fi.FullName;
                    using (FileStream fs = File.Open(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) //new FileStream(bundleFilename, FileMode.Open, FileAccess.Read))
                    {
                        byte[] data = new byte[fi.Length];
                        await fs.ReadAsync(data, 0, data.Length);

                        return(data);
                    }
                }
            }

            return(null);
        }
Beispiel #5
0
        private byte[] GetCompactTileBytes(IServiceRequestContext context, string path, int row, int col, string format)
        {
            string compactTileName = CompactTileName(row, col);

            string bundleFilename      = path + @"\" + compactTileName + ".tilebundle";
            string bundleIndexFilename = path + @"\" + compactTileName + ".tilebundlx";

            FileInfo fi = new FileInfo(bundleIndexFilename);

            if (!fi.Exists)
            {
                return(CreateEmpty(format));
            }

            CompactTileIndex bundleIndex = new CompactTileIndex(bundleIndexFilename);

            int bundleStartRow = CompactTileStart(row);
            int bundleStartCol = CompactTileStart(col);

            try
            {
                int tileLength, tilePosition = bundleIndex.TilePosition(row - bundleStartRow, col - bundleStartCol, out tileLength);

                if (tilePosition < 0)
                {
                    return(CreateEmpty(format));
                }

                using (FileStream fs = File.Open(bundleFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) //new FileStream(bundleFilename, FileMode.Open, FileAccess.Read))
                {
                    fs.Position = tilePosition;

                    byte[] data = new byte[tileLength];
                    fs.Read(data, 0, tileLength);
                    return(data);
                }
            }
            catch (Exception ex)
            {
                using (var serviceMap = context.CreateServiceMapInstance())
                {
                    TileServiceMetadata metadata = serviceMap.MetadataProvider(_metaprovider) as TileServiceMetadata;
                    using (System.Drawing.Bitmap bm = new Bitmap(metadata.TileWidth, metadata.TileHeight))
                        using (System.Drawing.Graphics gr = Graphics.FromImage(bm))
                            using (System.Drawing.Font font = new Font("Arial", 9f))
                            {
                                gr.DrawString(ex.Message, font, Brushes.Red, new RectangleF(0f, 0f, (float)bm.Width, (float)bm.Height));

                                MemoryStream ms = new MemoryStream();
                                bm.Save(ms, format == ".png" ? ImageFormat.Png : ImageFormat.Jpeg);

                                return(ms.ToArray());
                            }
                }
            }
        }
Beispiel #6
0
        private double GetScale(TileServiceMetadata metadata, string scaleArgument)
        {
            if (scaleArgument.StartsWith("~"))
            {
                scaleArgument = scaleArgument.Substring(1);
                int index = int.Parse(scaleArgument);
                if (index < 0 || index >= metadata.Scales.Count())
                {
                    return(0D);
                }

                return(metadata.Scales[int.Parse(scaleArgument)]);
            }
            return(double.Parse(scaleArgument.Replace(",", "."), _nhi));
        }
Beispiel #7
0
        private string TmsCapabilities(IServiceRequestContext context, TileServiceMetadata metadata, int srs)
        {
            IEnvelope box = metadata.GetEPSGEnvelope(srs);

            if (box == null)
            {
                return(String.Empty);
            }

            ISpatialReference sRef = SpatialReference.FromID("epsg:" + srs);

            StringBuilder sb = new StringBuilder();

            sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.Append("<TileMap version=\"1.0.0\" tilemapservice=\"" + context.ServiceRequest.OnlineResource + "\" >");
            sb.Append("<Title>" + context.ServiceMap.Name + "</Title>");
            sb.Append("<Abstract>gView Tile Cache</Abstract>");
            sb.Append("<SRS>EPSG:" + srs + "</SRS>");

            sb.Append("<BoundingBox minx=\"" + box.minx.ToString(_nhi) +
                      "\" miny=\"" + box.miny.ToString(_nhi) +
                      "\" maxx=\"" + box.maxx.ToString(_nhi) +
                      "\" maxy=\"" + box.maxy.ToString(_nhi) + "\" />");
            sb.Append("<Origin x=\"" + box.minx.ToString(_nhi) +
                      "\" y=\"" + box.miny.ToString(_nhi) + "\" />");

            sb.Append("<TileFormat width=\"" + metadata.TileWidth + "\" height=\"" + metadata.TileHeight + "\" mime-type=\"image/png\" extension=\"png\" />");
            sb.Append("<TileSets>");

            int level = 0;

            foreach (double scale in metadata.Scales)
            {
                double res = (double)scale / (metadata.Dpi / 0.0254);
                if (sRef.SpatialParameters.IsGeographic)
                {
                    GeoUnitConverter converter = new GeoUnitConverter();
                    res = converter.Convert(res, GeoUnits.Meters, GeoUnits.DecimalDegrees);
                }
                sb.Append("<TileSet href=\"" + context.ServiceRequest.OnlineResource + "/" + level + "\" ");
                sb.Append("units-per-pixel=\"" + res.ToString(_nhi) + "\" order=\"" + level + "\" />");
                level++;
            }
            sb.Append("</TileSets>");

            sb.Append("</TileMap>");
            return(sb.ToString());
        }
Beispiel #8
0
        private void WriteConfFile(IServiceRequestContext context, TileServiceMetadata metadata, string cacheFormat, int epsg, string format, GridOrientation orientation)
        {
            FileInfo configFileInfo = new FileInfo(_mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\" + cacheFormat + @"\" + TileServiceMetadata.EpsgPath(orientation, epsg) + @"\conf.json");

            IPoint    origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg);
            IEnvelope bounds = metadata.GetEPSGEnvelope(epsg);

            if (origin == null || bounds == null)
            {
                return;
            }

            List <CompactTileConfig.LevelConfig> levels = new List <CompactTileConfig.LevelConfig>();

            for (int i = 0; i < metadata.Scales.Count; i++)
            {
                levels.Add(new CompactTileConfig.LevelConfig()
                {
                    Level = i,
                    Scale = metadata.Scales[i]
                });
            }

            CompactTileConfig config = new CompactTileConfig()
            {
                Epsg        = epsg,
                Dpi         = metadata.Dpi,
                Origin      = new double[] { origin.X, origin.Y },
                Extent      = new double[] { bounds.minx, bounds.miny, bounds.maxx, bounds.maxy },
                TileSize    = new int[] { metadata.TileWidth, metadata.TileHeight },
                Format      = format,
                Orientation = orientation.ToString(),
                Levels      = levels.ToArray()
            };

            if (configFileInfo.Exists)
            {
                configFileInfo.Delete();
            }

            if (!configFileInfo.Directory.Exists)
            {
                configFileInfo.Directory.Create();
            }
            File.WriteAllText(configFileInfo.FullName, JsonConvert.SerializeObject(config, Formatting.Indented));
        }
Beispiel #9
0
 public TileRenderer(TileServiceMetadata metadata,
                     int epsg,
                     GridOrientation orientation = GridOrientation.UpperLeft,
                     string cacheFormat = "compact",
                     string imageFormat = ".png",
                     IEnvelope bbox = null,
                     IEnumerable<double> preRenderScales = null,
                     int maxParallelRequests = 1)
 {
     _metadata = metadata;
     _epsg = epsg;
     _orientation = orientation;
     _cacheFormat = cacheFormat;
     _imageFormat = imageFormat;
     _bbox = bbox;
     _preRenderScales = preRenderScales;
     _maxParallelRequests = maxParallelRequests;
 }
        public static TileServiceMetadata FromService(this TileServiceMetadata metadata, string server, string service)
        {
            var url = server.ToWmtsUrl(service, "GetMetadata");

            using (var client = new HttpClient())
            {
                var response = client.GetAsync(url).Result;
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception($"{ url } return with status code { response.StatusCode }");
                }

                var       responseStream = response.Content.ReadAsStreamAsync().Result;
                XmlStream xmlStream      = new XmlStream("WmtsMetadata");
                xmlStream.ReadStream(responseStream);

                return(xmlStream.Load("TileServiceMetadata") as TileServiceMetadata);
            }
        }
Beispiel #11
0
        private void GetCompactTileBytes(IServiceRequestContext context, string path, int row, int col)
        {
            string compactTileName = CompactTileName(row, col);

            string bundleFilename      = path + @"\" + compactTileName + ".tilebundle";
            string bundleIndexFilename = path + @"\" + compactTileName + ".tilebundlx";

            FileInfo fi = new FileInfo(bundleIndexFilename);

            if (!fi.Exists)
            {
                return;
            }

            CompactTileIndex bundleIndex = new CompactTileIndex(bundleIndexFilename);

            int bundleStartRow = CompactTileStart(row);
            int bundleStartCol = CompactTileStart(col);

            try
            {
                int tileLength, tilePosition = bundleIndex.TilePosition(row - bundleStartRow, col - bundleStartCol, out tileLength);

                if (tilePosition < 0)
                {
                    return;
                }

                using (FileStream fs = File.Open(bundleFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) //new FileStream(bundleFilename, FileMode.Open, FileAccess.Read))
                {
                    fs.Position = tilePosition;

                    byte[] data = new byte[tileLength];
                    fs.Read(data, 0, tileLength);

                    context.ServiceRequest.Response = new MapServerResponse()
                    {
                        Data        = data,
                        ContentType = "image/jpg",
                        Expires     = DateTime.UtcNow.AddDays(7)
                    }.ToString();
                }
            }
            catch (Exception ex)
            {
                TileServiceMetadata metadata = context.ServiceMap.MetadataProvider(_metaprovider) as TileServiceMetadata;
                using (System.Drawing.Bitmap bm = new Bitmap(metadata.TileWidth, metadata.TileHeight))
                    using (System.Drawing.Graphics gr = Graphics.FromImage(bm))
                        using (System.Drawing.Font font = new Font("Arial", 9f))
                        {
                            gr.DrawString(ex.Message, font, Brushes.Red, new RectangleF(0f, 0f, (float)bm.Width, (float)bm.Height));

                            MemoryStream ms = new MemoryStream();
                            bm.Save(ms, ImageFormat.Png);

                            context.ServiceRequest.Response = new MapServerResponse()
                            {
                                Data        = ms.ToArray(),
                                ContentType = "image/jpg"
                            }.ToString();
                        }
            }
        }
Beispiel #12
0
        private void GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation, BoundingTiles boundingTiles, bool renderOnTheFly)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            if (orientation != GridOrientation.UpperLeft)
            {
                throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!");
            }

            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);
            IPoint origin = metadata.GetOriginUpperLeft(epsg);

            if (origin == null)
            {
                throw new Exception("No origin defined for EPSG:" + epsg);
            }

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }
            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }
            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" +
                          TileServiceMetadata.ScalePath(orientation, epsg, scale);

            string compactTileName = CompactTileName(row, col);

            string bundleFilename     = path + @"\" + compactTileName + ".tilebundle";
            string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done";
            string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc";

            if (new FileInfo(bundleFilename).Exists)
            {
                GetCompactTileBytes(context, path, row, col);
                return;
            }
            else if (!renderOnTheFly || new FileInfo(bundleDoneFilename).Exists || new FileInfo(bundleCalcFilename).Exists /* && !metadata.RenderTilesOnTheFly*/)
            {
                return; // Empty
            }

            DirectoryInfo di = new DirectoryInfo(path);

            if (!di.Exists)
            {
                di.Create();
            }

            try { File.Delete(bundleFilename); }
            catch { }

            //temp
            //string pathTemp = path + @"\temp";
            //DirectoryInfo diTemp = new DirectoryInfo(pathTemp);
            //if (!diTemp.Exists)
            //    diTemp.Create();

            File.WriteAllText(bundleCalcFilename, "calc...");
            CompactTilesIndexBuilder indexBuilder = new CompactTilesIndexBuilder();

            int startRow = CompactTileStart(row), startCol = CompactTileStart(col);

            ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg);

            using (IServiceMap map = context.ServiceMap)
            {
                map.Display.SpatialReference = sRef;
                map.Display.dpi = metadata.Dpi;

                double res = (double)scale / (metadata.Dpi / 0.0254);
                if (map.Display.MapUnits != GeoUnits.Meters)
                {
                    GeoUnitConverter converter = new GeoUnitConverter();
                    res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                }


                string bundleTempFilename  = path + @"\" + compactTileName + "." + Guid.NewGuid().ToString("N").ToLower() + ".tilebundle";
                string bundleIndexFilename = path + @"\" + compactTileName + ".tilebundlx";

                File.WriteAllBytes(bundleTempFilename, new byte[0]);
                int bundlePos = 0;

                int tileMatrixWidth = 8, tileMatrixHeight = 8;

                map.Display.iWidth  = metadata.TileWidth * tileMatrixWidth;
                map.Display.iHeight = metadata.TileHeight * tileMatrixHeight;

                for (int r = 0; r < 128; r += 8)
                {
                    File.WriteAllText(bundleCalcFilename, "calc...row" + r);
                    for (int c = 0; c < 128; c += 8)
                    {
                        int currentRow = r + startRow, currentCol = c + startCol;

                        if (boundingTiles != null)
                        {
                            if (!boundingTiles.Check(currentRow, currentCol, 8, 8))
                            {
                                continue;
                            }
                        }

                        double H = metadata.TileHeight * res;
                        double y = origin.Y - H * (currentRow + tileMatrixHeight);

                        double W = metadata.TileWidth * res;
                        double x = origin.X + W * currentCol;

                        map.Display.ZoomTo(new Envelope(x, y, x + W * tileMatrixWidth, y + H * tileMatrixHeight));
                        if (format != ".jpg") // Make PNG Transparent
                        {
                            map.Display.BackgroundColor = System.Drawing.Color.Transparent;
                        }

                        map.ReleaseImage();  // Delete old Image !!! Because there is no map.SaveImage()!!!!
                        map.Render();

                        if (IsEmptyBitmap(map.MapImage, map.Display.BackgroundColor))
                        {
                            continue;
                        }

                        // Temp
                        //map.MapImage.Save(pathTemp + @"\matrix_" + (startRow + r) + "_" + (startCol + c) + ".png", ImageFormat.Png);

                        for (int j = 0; j < tileMatrixHeight; j++)
                        {
                            for (int i = 0; i < tileMatrixWidth; i++)
                            {
                                int tileRow = currentRow + j, tileCol = currentCol + i;

                                if (boundingTiles != null)
                                {
                                    if (!boundingTiles.Check(tileRow, tileCol, 8, 8))
                                    {
                                        continue;
                                    }
                                }

                                using (Bitmap bm = new Bitmap(metadata.TileWidth, metadata.TileHeight, map.MapImage.PixelFormat))
                                    using (Graphics gr = Graphics.FromImage(bm))
                                    {
                                        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                                        gr.DrawImage(map.MapImage,
                                                     new RectangleF(0f, 0f, (float)bm.Width, (float)bm.Height),
                                                     new RectangleF(-0.5f + (float)(i * metadata.TileWidth), -0.5f + (float)(j * metadata.TileHeight), (float)metadata.TileWidth, (float)metadata.TileHeight), GraphicsUnit.Pixel);

                                        //for (int py = 0, to_py = bm.Height; py < to_py; py++)
                                        //{
                                        //    for (int px = 0, to_px = bm.Width; px < to_px; px++)
                                        //    {
                                        //        var pCol = map.MapImage.GetPixel(px + i * metadata.TileHeight, py + j * metadata.TileHeight);
                                        //        bm.SetPixel(px, py, pCol);
                                        //    }
                                        //}

                                        if (IsEmptyBitmap(bm, map.Display.BackgroundColor))
                                        {
                                            continue;
                                        }

                                        // Temp
                                        //bm.Save(pathTemp + @"\tile_" + tileRow + "_" + tileCol + ".png", ImageFormat.Png);

                                        //try
                                        //{
                                        //    if (format != ".jpg" && map.Display.BackgroundColor.A > 0)   // Make PNG Transparent
                                        //        bm.MakeTransparent(map.Display.BackgroundColor);
                                        //}
                                        //catch { }

                                        MemoryStream ms = new MemoryStream();
                                        bm.Save(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);


                                        byte[] imageBytes = ms.ToArray();
                                        using (var stream = new FileStream(bundleTempFilename, FileMode.Append))
                                        {
                                            stream.Write(imageBytes, 0, imageBytes.Length);
                                        }

                                        indexBuilder.SetValue(r + j, c + i, bundlePos, imageBytes.Length);

                                        bundlePos += imageBytes.Length;
                                    }
                            }
                        }
                    }

                    map.ReleaseImage();
                    GC.Collect();
                }

                try { File.Delete(bundleFilename); }
                catch { }
                if (bundlePos == 0)
                {
                    File.Delete(bundleTempFilename);
                    File.WriteAllText(bundleDoneFilename, "");
                }
                else
                {
                    File.Move(bundleTempFilename, bundleFilename);
                    indexBuilder.Save(bundleIndexFilename);
                }
                try { File.Delete(bundleCalcFilename); }
                catch { }
            }
            GC.Collect();
        }
Beispiel #13
0
        public void Request(IServiceRequestContext context)
        {
            try
            {
                if (context == null || context.ServiceRequest == null || context.ServiceMap == null)
                {
                    return;
                }

                if (_mapServer == null)
                {
                    context.ServiceRequest.Response = "<FATALERROR>MapServer Object is not available!</FATALERROR>";
                    return;
                }

                TileServiceMetadata metadata = context.ServiceMap.MetadataProvider(_metaprovider) as TileServiceMetadata;
                if (metadata == null || metadata.Use == false)
                {
                    context.ServiceRequest.Response = "<ERROR>Service is not used with Tile Service</ERROR>";
                }

                string service = context.ServiceRequest.Service;
                string request = context.ServiceRequest.Request;
                if (request.ToLower().StartsWith("path="))
                {
                    request = request.Substring(5);
                }

                string[] args = request.Split('/');

                string command        = args[0].ToLower();
                bool   renderOnTheFly = false;
                if (command.Contains(":"))
                {
                    switch (command.Split(':')[1])
                    {
                    case "render":
                        renderOnTheFly = true;
                        break;
                    }

                    command = command.Split(':')[0];
                }

                switch (command)
                {
                case "metadata":
                    XmlStream stream = new XmlStream("metadata");
                    metadata.Save(stream);
                    StringWriter sw = new StringWriter();
                    stream.WriteStream(sw);
                    sw.Close();
                    context.ServiceRequest.Response = sw.ToString();
                    break;

                case "osm":
                case "tms":
                    if (args.Length == 4)
                    {
                        int epsg = int.Parse(args[1]);
                        if (metadata.EPSGCodes.Contains(epsg))
                        {
                            context.ServiceRequest.Response = TmsCapabilities(context, metadata, epsg);
                        }
                    }
                    else if (args.Length == 7)     // tms/srs/1.0.0/service/0/0/0.png
                    {
                        int    epsg   = int.Parse(args[1]);
                        double scale  = metadata.Scales[int.Parse(args[4])];
                        int    row    = (args[0] == "tms" ? int.Parse(args[5]) : int.Parse(args[6].Split('.')[0]));
                        int    col    = (args[0] == "tms" ? int.Parse(args[6].Split('.')[0]) : int.Parse(args[5]));
                        string format = ".png";
                        if (args[6].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        GetTile(context, metadata, epsg, scale, row, col, format, (args[0] == "tms" ? GridOrientation.LowerLeft : GridOrientation.UpperLeft), renderOnTheFly);
                    }
                    else if (args.Length == 10)      // tms/srs/service/01/000/000/001/000/000/001.png
                    {
                        int    epsg   = int.Parse(args[1]);
                        double scale  = metadata.Scales[int.Parse(args[3])];
                        int    col    = int.Parse(args[4]) * 1000000 + int.Parse(args[5]) * 1000 + int.Parse(args[6]);
                        int    row    = int.Parse(args[7]) * 1000000 + int.Parse(args[8]) * 1000 + int.Parse(args[9].Split('.')[0]);
                        string format = ".png";
                        if (args[9].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        GetTile(context, metadata, epsg, scale, row, col, format, (args[0] == "tms" ? GridOrientation.LowerLeft : GridOrientation.UpperLeft), renderOnTheFly);
                    }
                    break;

                case "init":
                    if (args.Length >= 5)
                    {
                        string cacheFormat = args[1].ToLower() == "compact" ? "compact" : "";
                        if (args[2].ToLower() != "ul" &&
                            args[2].ToLower() != "ll")
                        {
                            throw new ArgumentException();
                        }

                        int    epsg   = int.Parse(args[3]);
                        string format = "image/" + args[4].ToLower();
                        if (args[4].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        WriteConfFile(context, metadata, cacheFormat, epsg, format,
                                      (args[2].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft));
                    }
                    break;

                case "tile":
                    if (args.Length == 5)
                    {
                        int    epsg   = int.Parse(args[1]);
                        double scale  = GetScale(metadata, args[2]);    // double.Parse(args[2].Replace(",", "."), _nhi);
                        int    row    = int.Parse(args[3]);
                        int    col    = int.Parse(args[4].Split('.')[0]);
                        string format = ".png";
                        if (args[4].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        GetTile(context, metadata, epsg, scale, row, col, format, GridOrientation.UpperLeft, renderOnTheFly);
                    }
                    else if (args.Length == 6)
                    {
                        if (args[1].ToLower() != "ul" &&
                            args[1].ToLower() != "ll")
                        {
                            throw new ArgumentException();
                        }

                        int    epsg   = int.Parse(args[2]);
                        double scale  = GetScale(metadata, args[3]);    // double.Parse(args[3].Replace(",", "."), _nhi);
                        int    row    = int.Parse(args[4]);
                        int    col    = int.Parse(args[5].Split('.')[0]);
                        string format = ".png";
                        if (args[5].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        GetTile(context, metadata, epsg, scale, row, col, format,
                                (args[1].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft), renderOnTheFly);
                    }
                    else if (args.Length >= 7)
                    {
                        string cacheFormat = args[1].ToLower();
                        if (args[2].ToLower() != "ul" &&
                            args[2].ToLower() != "ll")
                        {
                            throw new ArgumentException();
                        }

                        int    epsg   = int.Parse(args[3]);
                        double scale  = GetScale(metadata, args[4]);    // double.Parse(args[4].Replace(",", "."), _nhi);
                        int    row    = int.Parse(args[5]);
                        int    col    = int.Parse(args[6].Split('.')[0]);
                        string format = ".png";
                        if (args[6].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        if (cacheFormat == "compact")
                        {
                            var boundingTiles = args.Length > 7 ? new BoundingTiles(args[7]) : null;

                            GetCompactTile(context, metadata, epsg, scale, row, col, format,
                                           (args[2].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft), boundingTiles, renderOnTheFly);
                        }
                        else
                        {
                            GetTile(context, metadata, epsg, scale, row, col, format,
                                    (args[2].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft), renderOnTheFly);
                        }
                    }
                    else
                    {
                        throw new ArgumentException();
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                if (context != null && context.ServiceRequest != null)
                {
                    context.ServiceRequest.Response = "<Exception>" + ex.Message + "</Exception>";
                }
            }
        }
Beispiel #14
0
        private void GetTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation, bool renderOnTheFly)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            //if (!metadata.Scales.Contains(scale))
            //    throw new ArgumentException("Wrong scale argument");
            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEPSGEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }
            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }
            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\" +
                          TileServiceMetadata.TilePath(orientation, epsg, scale, row, col) + format;

            if ((orientation == GridOrientation.UpperLeft && metadata.UpperLeftCacheTiles) ||
                (orientation == GridOrientation.LowerLeft && metadata.LowerLeftCacheTiles))
            {
                FileInfo fi = new FileInfo(path);
                if (fi.Exists)
                {
                    context.ServiceRequest.Response = fi.FullName;
                    return;
                }
                else if (!renderOnTheFly && !metadata.RenderTilesOnTheFly)
                {
                    return;  // Empty
                }
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
            }
            else
            {
                path = _mapServer.OutputPath + @"\tile_" + Guid.NewGuid().ToString("N").ToLower() + format;
            }

            ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg);

            using (IServiceMap map = context.ServiceMap)
            {
                map.Display.SpatialReference = sRef;
                map.Display.dpi = metadata.Dpi;

                map.Display.iWidth  = metadata.TileWidth;
                map.Display.iHeight = metadata.TileHeight;

                double res = (double)scale / (metadata.Dpi / 0.0254);
                if (map.Display.MapUnits != GeoUnits.Meters)
                {
                    GeoUnitConverter converter = new GeoUnitConverter();
                    res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                }

                var origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg);

                double H = metadata.TileHeight * res;
                double y = (orientation == GridOrientation.UpperLeft ?
                            origin.Y - H * (row + 1) :
                            origin.Y + H * row);

                double W = metadata.TileWidth * res;
                //if (map.Display.MapUnits == GeoUnits.DecimalDegrees)
                //{
                //    double phi = (2 * y + H) / 2.0;
                //    W /= Math.Cos(phi / 180.0 * Math.PI);
                //}
                double x = origin.X + W * col;

                map.Display.ZoomTo(new Envelope(x, y, x + W, y + H));
                map.Render();

                bool maketrans = map.Display.MakeTransparent;
                map.Display.MakeTransparent = true;
                map.SaveImage(path, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);
                map.Display.MakeTransparent = maketrans;

                context.ServiceRequest.Response = path;
                _mapServer.Log("CreateTile:", loggingMethod.request_detail, path);
            }
        }
Beispiel #15
0
        private byte[] GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            if (orientation != GridOrientation.UpperLeft)
            {
                throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!");
            }

            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);
            IPoint origin = metadata.GetOriginUpperLeft(epsg);

            if (origin == null)
            {
                throw new Exception("No origin defined for EPSG:" + epsg);
            }

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }
            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }
            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"\" + MapName(context) + @"\_alllayers\compact\" +
                          TileServiceMetadata.ScalePath(orientation, epsg, scale);

            string compactTileName = CompactTileName(row, col);

            string bundleFilename     = path + @"\" + compactTileName + ".tilebundle";
            string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done";
            string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc";

            if (new FileInfo(bundleFilename).Exists)
            {
                return(GetCompactTileBytes(context, path, row, col, format));
            }



            if (IsDirectoryEmpty(path))
            {
                #region On The Fly

                using (IServiceMap map = context.CreateServiceMapInstance())
                {
                    ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg);

                    map.Display.SpatialReference = sRef;
                    map.Display.dpi = metadata.Dpi;

                    map.Display.iWidth  = metadata.TileWidth;
                    map.Display.iHeight = metadata.TileHeight;

                    double res = (double)scale / (metadata.Dpi / 0.0254);
                    if (map.Display.MapUnits != GeoUnits.Meters)
                    {
                        GeoUnitConverter converter = new GeoUnitConverter();
                        res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                    }

                    origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg);

                    double H = metadata.TileHeight * res;
                    double y = (orientation == GridOrientation.UpperLeft ?
                                origin.Y - H * (row + 1) :
                                origin.Y + H * row);

                    double W = metadata.TileWidth * res;
                    double x = origin.X + W * col;

                    map.Display.ZoomTo(new Envelope(x, y, x + W, y + H));
                    map.Render();

                    bool maketrans = map.Display.MakeTransparent;
                    map.Display.MakeTransparent = true;
                    MemoryStream ms = new MemoryStream();
                    map.SaveImage(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);
                    map.Display.MakeTransparent = maketrans;

                    return(ms.ToArray());
                }

                #endregion
            }


            return(null);
        }
Beispiel #16
0
        private void WmtsCapabilities100(IServiceRequestContext context, TileServiceMetadata metadata)
        {
            gView.Framework.OGC.WMTS.Version_1_0_0.Capabilities capabilities = new Framework.OGC.WMTS.Version_1_0_0.Capabilities()
            {
                version = "1.0.0"
            };

            capabilities.NameSpaces = new System.Xml.Serialization.XmlSerializerNamespaces();
            capabilities.NameSpaces.Add("ows", "http://www.opengis.net/ows/1.1");
            capabilities.NameSpaces.Add("xlink", "http://www.w3.org/1999/xlink");
            capabilities.NameSpaces.Add("gml", "http://www.opengis.net/gml");

            #region ServiceIndentification

            capabilities.ServiceIdentification       = new gView.Framework.OGC.WMTS.Version_1_0_0.ServiceIdentification();
            capabilities.ServiceIdentification.Title = new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType()
                                                                                                                         {
                                                                                                                             Value = context.ServiceMap.Name
                                                                                                                         } };
            capabilities.ServiceIdentification.ServiceType = new gView.Framework.OGC.WMTS.Version_1_0_0.CodeType()
            {
                Value = "OGC WMTS"
            };
            capabilities.ServiceIdentification.ServiceTypeVersion = new string[] { "1.0.0" };

            #endregion

            string restFulUrl = context.ServiceRequest.OnlineResource.ToLower().Replace("/maprequest/wmts/", "/tilewmts/");

            #region OperationsMetadata

            capabilities.OperationsMetadata = new gView.Framework.OGC.WMTS.Version_1_0_0.OperationsMetadata();

            var getCapOperation = new gView.Framework.OGC.WMTS.Version_1_0_0.Operation()
            {
                name = "GetCapabilities"
            };
            getCapOperation.DCP               = new gView.Framework.OGC.WMTS.Version_1_0_0.DCP[] { new gView.Framework.OGC.WMTS.Version_1_0_0.DCP() };
            getCapOperation.DCP[0].Item       = new gView.Framework.OGC.WMTS.Version_1_0_0.HTTP();
            getCapOperation.DCP[0].Item.Items = new gView.Framework.OGC.WMTS.Version_1_0_0.RequestMethodType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.RequestMethodType() };

            getCapOperation.DCP[0].Item.Items[0].href                        = context.ServiceRequest.OnlineResource + "?SERVICE=WMTS&VERSION=1.0.0" + "&";
            getCapOperation.DCP[0].Item.Items[0].Constraint                  = new gView.Framework.OGC.WMTS.Version_1_0_0.DomainType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.DomainType() };
            getCapOperation.DCP[0].Item.Items[0].Constraint[0].name          = "GetEncoding";
            getCapOperation.DCP[0].Item.Items[0].Constraint[0].AllowedValues = new object[] { new gView.Framework.OGC.WMTS.Version_1_0_0.ValueType()
                                                                                              {
                                                                                                  Value = "KVP"                                                      /*"RESTful"*/
                                                                                              } };
            getCapOperation.DCP[0].Item.ItemsElementName = new gView.Framework.OGC.WMTS.Version_1_0_0.ItemsChoiceType[] { gView.Framework.OGC.WMTS.Version_1_0_0.ItemsChoiceType.Get };


            var getTileOperation = new gView.Framework.OGC.WMTS.Version_1_0_0.Operation()
            {
                name = "GetTile"
            };
            getTileOperation.DCP               = new gView.Framework.OGC.WMTS.Version_1_0_0.DCP[] { new gView.Framework.OGC.WMTS.Version_1_0_0.DCP() };
            getTileOperation.DCP[0].Item       = new gView.Framework.OGC.WMTS.Version_1_0_0.HTTP();
            getTileOperation.DCP[0].Item.Items = new gView.Framework.OGC.WMTS.Version_1_0_0.RequestMethodType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.RequestMethodType() };

            getTileOperation.DCP[0].Item.Items[0].href                        = restFulUrl;
            getTileOperation.DCP[0].Item.Items[0].Constraint                  = new gView.Framework.OGC.WMTS.Version_1_0_0.DomainType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.DomainType() };
            getTileOperation.DCP[0].Item.Items[0].Constraint[0].name          = "GetEncoding";
            getTileOperation.DCP[0].Item.Items[0].Constraint[0].AllowedValues = new object[] { new gView.Framework.OGC.WMTS.Version_1_0_0.ValueType()
                                                                                               {
                                                                                                   Value = "RESTful"
                                                                                               } };
            getTileOperation.DCP[0].Item.ItemsElementName = new gView.Framework.OGC.WMTS.Version_1_0_0.ItemsChoiceType[] { gView.Framework.OGC.WMTS.Version_1_0_0.ItemsChoiceType.Get };

            capabilities.OperationsMetadata.Operation = new gView.Framework.OGC.WMTS.Version_1_0_0.Operation[]
            {
                getCapOperation, getTileOperation
            };

            #endregion

            #region Contents

            capabilities.Contents = new gView.Framework.OGC.WMTS.Version_1_0_0.ContentsType();

            List <gView.Framework.OGC.WMTS.Version_1_0_0.LayerType>     layers     = new List <gView.Framework.OGC.WMTS.Version_1_0_0.LayerType>();
            List <gView.Framework.OGC.WMTS.Version_1_0_0.TileMatrixSet> matrixSets = new List <gView.Framework.OGC.WMTS.Version_1_0_0.TileMatrixSet>();

            ISpatialReference sRef4326 = SpatialReference.FromID("epsg:4326");

            foreach (var epsg in metadata.EPSGCodes)
            {
                IEnvelope extent = metadata.GetEPSGEnvelope(epsg);
                if (extent == null)
                {
                    continue;
                }
                IPoint origin = metadata.GetOriginUpperLeft(epsg);
                if (origin == null)
                {
                    continue;
                }

                ISpatialReference sRef       = SpatialReference.FromID("epsg:" + epsg);
                IEnvelope         extent4326 = GeometricTransformer.Transform2D(extent, sRef, sRef4326).Envelope;

                if (double.IsInfinity(extent4326.minx))
                {
                    extent4326.minx = -180D;
                }
                if (double.IsInfinity(extent4326.miny))
                {
                    extent4326.miny = -90D;
                }
                if (double.IsInfinity(extent4326.maxx))
                {
                    extent4326.maxx = 180D;
                }
                if (double.IsInfinity(extent4326.maxy))
                {
                    extent4326.maxy = 90D;
                }

                foreach (string cacheType in new string[] { "classic", "compact" })
                {
                    string epsgPath = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\" + (cacheType == "compact" ? @"compact\" : "") +
                                      TileServiceMetadata.EpsgPath(GridOrientation.UpperLeft, epsg);

                    if (!new DirectoryInfo(epsgPath).Exists)
                    {
                        continue;
                    }

                    #region Layer

                    string layerName = context.ServiceMap.Name + " EPSG:" + epsg + " " + cacheType;
                    string layerId   = context.ServiceMap.Name.ToLower().Replace(" ", "_") + "_" + epsg + "_" + cacheType;

                    var layer = new gView.Framework.OGC.WMTS.Version_1_0_0.LayerType();

                    layer.Title = new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType()
                                                                                                    {
                                                                                                        Value = layerName
                                                                                                    } };
                    layer.Identifier = new gView.Framework.OGC.WMTS.Version_1_0_0.CodeType()
                    {
                        Value = layerId
                    };

                    List <gView.Framework.OGC.WMTS.Version_1_0_0.Style> styles = new List <Framework.OGC.WMTS.Version_1_0_0.Style>();
                    //styles.Add(new gView.Framework.OGC.WMTS.Version_1_0_0.Style()
                    //{
                    //    Title = new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType() { Value = "Default Style" } },
                    //    Identifier = new gView.Framework.OGC.WMTS.Version_1_0_0.CodeType() { Value = "default" }
                    //});
                    foreach (var styleVal in Enum.GetValues(typeof(ImageProcessingFilters)))
                    {
                        string name = Enum.GetName(typeof(ImageProcessingFilters), styleVal);
                        styles.Add(new Framework.OGC.WMTS.Version_1_0_0.Style()
                        {
                            Title = new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType()
                                                                                                      {
                                                                                                          Value = name
                                                                                                      } },
                            Identifier = new gView.Framework.OGC.WMTS.Version_1_0_0.CodeType()
                            {
                                Value = name.ToLower()
                            }
                        });
                    }

                    layer.Style = styles.ToArray();

                    #region BoundingBox

                    layer.BoundingBox = new gView.Framework.OGC.WMTS.Version_1_0_0.BoundingBoxType[]
                    {
                        new gView.Framework.OGC.WMTS.Version_1_0_0.BoundingBoxType()
                        {
                            crs         = "urn:ogc:def:crs:EPSG::" + epsg,
                            LowerCorner = PointToString(extent.LowerLeft, sRef),
                            UpperCorner = PointToString(extent.UpperRight, sRef)
                        }
                    };
                    layer.WGS84BoundingBox = new gView.Framework.OGC.WMTS.Version_1_0_0.WGS84BoundingBoxType[]
                    {
                        new gView.Framework.OGC.WMTS.Version_1_0_0.WGS84BoundingBoxType()
                        {
                            crs         = "urn:ogc:def:crs:OGC:2:84", // urn:ogc:def:crs:OGC:2:84
                            LowerCorner = PointToString(extent4326.LowerLeft, sRef4326),
                            UpperCorner = PointToString(extent4326.UpperRight, sRef4326)
                        }
                    };

                    #endregion

                    layer.TileMatrixSetLink = new gView.Framework.OGC.WMTS.Version_1_0_0.TileMatrixSetLink[]
                    {
                        new gView.Framework.OGC.WMTS.Version_1_0_0.TileMatrixSetLink()
                        {
                            TileMatrixSet = layerId + "_default_matrixset"
                        }
                    };

                    List <string> formats = new List <string>();
                    if (metadata.FormatJpg)
                    {
                        formats.Add("image/jpg");
                    }
                    if (metadata.FormatPng)
                    {
                        formats.Add("image/png");
                    }
                    layer.Format = formats.ToArray();

                    List <Framework.OGC.WMTS.Version_1_0_0.URLTemplateType> resourceURLs = new List <Framework.OGC.WMTS.Version_1_0_0.URLTemplateType>();
                    if (metadata.FormatJpg)
                    {
                        resourceURLs.Add(new Framework.OGC.WMTS.Version_1_0_0.URLTemplateType()
                        {
                            resourceType = Framework.OGC.WMTS.Version_1_0_0.URLTemplateTypeResourceType.tile,
                            format       = "image/jpg",
                            template     = restFulUrl + "/" + cacheType + "/ul/" + epsg + "/{Style}/{TileMatrix}/{TileRow}/{TileCol}.jpg"
                        });
                    }
                    if (metadata.FormatPng)
                    {
                        resourceURLs.Add(new Framework.OGC.WMTS.Version_1_0_0.URLTemplateType()
                        {
                            resourceType = Framework.OGC.WMTS.Version_1_0_0.URLTemplateTypeResourceType.tile,
                            format       = "image/png",
                            template     = restFulUrl + "/" + cacheType + "/ul/" + epsg + "/{Style}/{TileMatrix}/{TileRow}/{TileCol}.png"
                        });
                    }
                    layer.ResourceURL = resourceURLs.ToArray();

                    layers.Add(layer);

                    #endregion

                    #region Matrix Set

                    double matrixSetWidth  = extent.Width;
                    double matrixSetHeight = extent.Height;

                    var matrixSet = new gView.Framework.OGC.WMTS.Version_1_0_0.TileMatrixSet();

                    matrixSet.Title = new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType[] { new gView.Framework.OGC.WMTS.Version_1_0_0.LanguageStringType()
                                                                                                        {
                                                                                                            Value = layerName + " Default Matrix Set"
                                                                                                        } };
                    matrixSet.Identifier = new gView.Framework.OGC.WMTS.Version_1_0_0.CodeType()
                    {
                        Value = layerId + "_default_matrixset"
                    };
                    matrixSet.SupportedCRS = "urn:ogc:def:crs:EPSG::" + epsg;

                    matrixSet.TileMatrix = new gView.Framework.OGC.WMTS.Version_1_0_0.TileMatrix[metadata.Scales.Count];

                    #region DPI

                    double inchMeter = 0.0254;                    /* 0.0254000508001016;*/
                    double dpi       = inchMeter * 1000D / 0.28D; // wmts 0.28mm -> 1 Pixel;
                    double dpm       = dpi / inchMeter;

                    #endregion

                    for (int s = 0, to = metadata.Scales.Count; s < to; s++)
                    {
                        string scalePath = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\" + (cacheType == "compact" ? @"compact\" : "") +
                                           TileServiceMetadata.ScalePath(GridOrientation.UpperLeft, epsg, metadata.Scales[s]);

                        if (!new DirectoryInfo(scalePath).Exists)
                        {
                            break;
                        }

                        double resolution = metadata.Scales[s] / (metadata.Dpi / inchMeter);

                        matrixSet.TileMatrix[s]            = new gView.Framework.OGC.WMTS.Version_1_0_0.TileMatrix();
                        matrixSet.TileMatrix[s].Identifier = new gView.Framework.OGC.WMTS.Version_1_0_0.CodeType()
                        {
                            Value = s.ToString()
                        };
                        matrixSet.TileMatrix[s].TopLeftCorner = PointToString(origin, sRef);
                        matrixSet.TileMatrix[s].TileWidth     = metadata.TileWidth.ToString();
                        matrixSet.TileMatrix[s].TileHeight    = metadata.TileHeight.ToString();

                        double tileWidth  = metadata.TileWidth * resolution;
                        double tileHeight = metadata.TileHeight * resolution;

                        int matrixWidth  = (int)Math.Round(matrixSetWidth / tileWidth + 0.5);
                        int matrixHeight = (int)Math.Round(matrixSetHeight / tileHeight + 0.5);

                        matrixSet.TileMatrix[s].MatrixWidth      = matrixWidth.ToString();
                        matrixSet.TileMatrix[s].MatrixHeight     = matrixHeight.ToString();
                        matrixSet.TileMatrix[s].ScaleDenominator = resolution * dpm;
                    }

                    matrixSets.Add(matrixSet);

                    #endregion
                }
            }

            capabilities.Contents.DatasetDescriptionSummary = layers.ToArray();
            capabilities.Contents.TileMatrixSet             = matrixSets.ToArray();

            #endregion

            XsdSchemaSerializer <gView.Framework.OGC.WMTS.Version_1_0_0.Capabilities> ser = new XsdSchemaSerializer <gView.Framework.OGC.WMTS.Version_1_0_0.Capabilities>();
            string xml = ser.Serialize(capabilities, null);

            xml = xml.Replace(@"<ows:DatasetDescriptionSummary xsi:type=""LayerType"">", "<Layer>");
            xml = xml.Replace(@"</ows:DatasetDescriptionSummary>", "</Layer>");

            context.ServiceRequest.Response = xml;
        }
Beispiel #17
0
        async private Task <byte[]> GetCompactTileBytes(IServiceRequestContext context, string path, int row, int col, string format)
        {
            string compactTileName = CompactTileName(row, col);

            string bundleFilename      = path + @"/" + compactTileName + ".tilebundle";
            string bundleIndexFilename = path + @"/" + compactTileName + ".tilebundlx";

            FileInfo fi = new FileInfo(bundleIndexFilename);

            if (!fi.Exists)
            {
                return(CreateEmpty(format));
            }

            CompactTileIndex bundleIndex = new CompactTileIndex(bundleIndexFilename);

            int bundleStartRow = CompactTileStart(row);
            int bundleStartCol = CompactTileStart(col);

            try
            {
                var tilePositionResult = await bundleIndex.TilePosition(row - bundleStartRow, col - bundleStartCol);

                int tileLength = tilePositionResult.tileLength, tilePosition = tilePositionResult.position;

                if (tilePosition < 0)
                {
                    return(CreateEmpty(format));
                }

                using (FileStream fs = File.Open(bundleFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) //new FileStream(bundleFilename, FileMode.Open, FileAccess.Read))
                {
                    fs.Position = tilePosition;

                    byte[] data = new byte[tileLength];
                    await fs.ReadAsync(data, 0, tileLength);

                    return(data);
                }
            }
            catch (Exception ex)
            {
                using (var serviceMap = await context.CreateServiceMapInstance())
                {
                    TileServiceMetadata metadata = serviceMap.MetadataProvider(_metaprovider) as TileServiceMetadata;
                    using (var bitmap = Current.Engine.CreateBitmap(metadata.TileWidth, metadata.TileHeight))
                        using (var canvas = bitmap.CreateCanvas())
                            using (var font = Current.Engine.CreateFont("Arial", 9f))
                                using (var redBrush = Current.Engine.CreateSolidBrush(ArgbColor.Red))
                                {
                                    canvas.DrawText(ex.Message, font, redBrush, new CanvasRectangleF(0f, 0f, bitmap.Width, bitmap.Height));
                                    canvas.Flush();

                                    MemoryStream ms = new MemoryStream();
                                    bitmap.Save(ms, format == ".png" ? ImageFormat.Png : ImageFormat.Jpeg);

                                    return(ms.ToArray());
                                }
                }
            }
        }
Beispiel #18
0
        static int Main(string[] args)
        {
            try
            {
                PlugInManager.InitSilent = true;

                Action          action = Action.None;
                string          server = String.Empty, service = String.Empty, cacheFormat = "normal";
                int             epsg = 0, maxParallelRequests = 1;
                GridOrientation orientation = GridOrientation.UpperLeft;
                IEnvelope       bbox        = null;
                List <int>      scales      = new List <int>();

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "-server")
                    {
                        server = args[++i];
                    }
                    if (args[i] == "-service")
                    {
                        service = args[++i];
                    }
                    if (args[i] == "-info")
                    {
                        action = Action.Info;
                    }
                    if (args[i] == "-render")
                    {
                        action = Action.Render;
                    }
                    if (args[i] == "-compact")
                    {
                        cacheFormat = "compact";
                    }
                    if (args[i] == "-epsg")
                    {
                        epsg = int.Parse(args[++i]);
                    }
                    if (args[i] == "-orientation")
                    {
                        switch (args[++i].ToLower())
                        {
                        case "ul":
                        case "upperleft":
                            orientation = GridOrientation.UpperLeft;
                            break;

                        case "ll":
                        case "lowerleft":
                            orientation = GridOrientation.LowerLeft;
                            break;
                        }
                    }
                    if (args[i] == "-bbox")
                    {
                        bbox = Envelope.FromBBox(args[++i]);
                    }
                    if (args[i] == "-scales")
                    {
                        scales.AddRange(args[++i].Split(',').Select(v => int.Parse(v)));
                    }
                    if (args[i] == "-threads")
                    {
                        maxParallelRequests = int.Parse(args[++i]);
                    }
                }

                if (action == Action.None ||
                    String.IsNullOrWhiteSpace(server) ||
                    String.IsNullOrWhiteSpace(service))
                {
                    Console.WriteLine("USAGE:");
                    Console.WriteLine("gView.Cmd.RenderTileCache <-info|-render> -server <server> -service <service>");
                    Console.WriteLine("       optional paramters: -epsg <epsg-code>                            [default: first]");
                    Console.WriteLine("                           -compact ... create a compact tile cache");
                    Console.WriteLine("                           -orientation <ul|ll|upperleft|lowerleft>     [default: upperleft]");
                    Console.WriteLine("                           -bbox <minx,miny,maxx,maxy>                  [default: fullextent]");
                    Console.WriteLine("                           -scales <scale1,scale2,...>                  [default: empty => all scales");
                    Console.WriteLine("                           -threads <max-parallel-requests>             [default: 1]");

                    return(1);
                }

                #region Read Metadata

                var metadata = new TileServiceMetadata().FromService(server, service);
                if (metadata == null)
                {
                    throw new Exception("Can't read metadata from server. Are you sure taht ervice is a gView WMTS service?");
                }

                #endregion

                if (action == Action.Info)
                {
                    #region TileSize

                    Console.WriteLine($"TileSize [Pixel]: { metadata.TileWidth } x { metadata.TileHeight }");

                    #endregion

                    #region ImageFormat

                    Console.Write("ImageFormats:");
                    Console.Write(metadata.FormatJpg ? " jpg" : "");
                    Console.Write(metadata.FormatPng ? " png" : "");
                    Console.WriteLine();

                    #endregion

                    #region Scales

                    Console.WriteLine("Scales:");
                    if (metadata.Scales != null)
                    {
                        foreach (var scale in metadata.Scales)
                        {
                            Console.WriteLine($"  1 : { scale }");
                        }
                    }

                    #endregion

                    #region Origin

                    Console.Write("Origin:");
                    Console.Write(metadata.UpperLeft ? " upperleft" : "");
                    Console.Write(metadata.LowerLeft ? " lowerleft" : "");
                    Console.WriteLine();

                    if (metadata.EPSGCodes != null)
                    {
                        foreach (var epsgCode in metadata.EPSGCodes)
                        {
                            if (metadata.UpperLeft)
                            {
                                var ul = metadata.GetOriginUpperLeft(epsgCode);
                                Console.WriteLine($"  EPSG:{ epsgCode } upperleft: { ul.X }, { ul.Y }");
                            }
                            if (metadata.LowerLeft)
                            {
                                var ll = metadata.GetOriginUpperLeft(epsgCode);
                                Console.WriteLine($"  EPSG:{ epsgCode } lowerleft: { ll.X }, { ll.Y }");
                            }
                        }
                    }

                    #endregion

                    #region Extents

                    Console.WriteLine("BBox:");
                    if (metadata.EPSGCodes != null)
                    {
                        foreach (var epsgCode in metadata.EPSGCodes)
                        {
                            var envelope = metadata.GetEPSGEnvelope(epsgCode);
                            if (envelope != null)
                            {
                                Console.WriteLine($"  EPSG:{ epsgCode }: { envelope.minx }, { envelope.miny }, { envelope.maxx }, { envelope.maxy }");
                            }
                        }
                    }

                    #endregion
                }
                else if (action == Action.Render)
                {
                    var startTime = DateTime.Now;

                    List <double> preRenderScales = new List <double>();
                    if (scales.Count > 0)
                    {
                        preRenderScales.AddRange(scales.Where(s => metadata.Scales.Contains(s)).Select(s => (double)s));
                    }

                    var tileRender = new TileRenderer(metadata,
                                                      epsg > 0 ? epsg : metadata.EPSGCodes.First(),
                                                      cacheFormat: cacheFormat,
                                                      orientation: orientation,
                                                      bbox: bbox,
                                                      preRenderScales: preRenderScales.Count > 0 ? preRenderScales : null,
                                                      maxParallelRequests: maxParallelRequests);

                    tileRender.Renderer(server, service);

                    Console.WriteLine();
                    Console.WriteLine($"Finished: { Math.Round((DateTime.Now - startTime).TotalSeconds) }sec");
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception:");
                Console.WriteLine(ex.Message);

                return(1);
            }
        }
Beispiel #19
0
        private void GetCompactTileBytes(IServiceRequestContext context, IServiceMap serviceMap, string path, int row, int col)
        {
            string compactTileName = CompactTileName(row, col);

            string bundleFilename      = path + @"\" + compactTileName + ".tilebundle";
            string bundleIndexFilename = path + @"\" + compactTileName + ".tilebundlx";

            FileInfo fi = new FileInfo(bundleIndexFilename);

            if (!fi.Exists)
            {
                return;
            }

            CompactTileIndex bundleIndex = new CompactTileIndex(bundleIndexFilename);

            int bundleStartRow = CompactTileStart(row);
            int bundleStartCol = CompactTileStart(col);

            try
            {
                int tileLength, tilePosition = bundleIndex.TilePosition(row - bundleStartRow, col - bundleStartCol, out tileLength);

                if (tilePosition < 0)
                {
                    return;
                }

                using (FileStream fs = File.Open(bundleFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) //new FileStream(bundleFilename, FileMode.Open, FileAccess.Read))
                {
                    fs.Position = tilePosition;

                    byte[] data = new byte[tileLength];
                    fs.Read(data, 0, tileLength);

                    context.ServiceRequest.Response = new MapServerResponse()
                    {
                        Data        = data,
                        ContentType = "image/jpg",
                        Expires     = DateTime.UtcNow.AddDays(7)
                    }.ToString();
                }
            }
            catch (Exception ex)
            {
                TileServiceMetadata metadata = serviceMap.MetadataProvider(_metaprovider) as TileServiceMetadata;
                using (var bitmap = Current.Engine.CreateBitmap(metadata.TileWidth, metadata.TileHeight))
                    using (var canvas = bitmap.CreateCanvas())
                        using (var font = Current.Engine.CreateFont("Arial", 9f))
                            using (var redBrush = Current.Engine.CreateSolidBrush(ArgbColor.Red))
                            {
                                canvas.DrawText(ex.Message, font, redBrush, new CanvasRectangleF(0f, 0f, (float)bitmap.Width, (float)bitmap.Height));
                                canvas.Flush();

                                MemoryStream ms = new MemoryStream();
                                bitmap.Save(ms, ImageFormat.Png);

                                context.ServiceRequest.Response = new MapServerResponse()
                                {
                                    Data        = ms.ToArray(),
                                    ContentType = "image/jpg"
                                }.ToString();
                            }
            }
        }
Beispiel #20
0
        private byte[] GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation)
        {
            if (!metadata.EPSGCodes.Contains(epsg))
            {
                throw new ArgumentException("Wrong epsg argument");
            }

            if (orientation != GridOrientation.UpperLeft)
            {
                throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!");
            }

            scale = metadata.Scales.GetScale(scale);
            if (scale <= 0.0)
            {
                throw new ArgumentException("Wrong scale argument");
            }

            //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg);
            //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0)
            //    throw new Exception("No bounds defined for EPSG:" + epsg);
            IPoint origin = metadata.GetOriginUpperLeft(epsg);

            if (origin == null)
            {
                throw new Exception("No origin defined for EPSG:" + epsg);
            }

            format = format.ToLower();
            if (format != ".png" && format != ".jpg")
            {
                throw new Exception("Unsupported image format");
            }
            if (format == ".png" && metadata.FormatPng == false)
            {
                throw new Exception("Format image/png not supported");
            }
            if (format == ".jpg" && metadata.FormatJpg == false)
            {
                throw new Exception("Format image/jpeg no supported");
            }

            string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" +
                          TileServiceMetadata.ScalePath(orientation, epsg, scale);

            string compactTileName = CompactTileName(row, col);

            string bundleFilename     = path + @"\" + compactTileName + ".tilebundle";
            string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done";
            string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc";

            if (new FileInfo(bundleFilename).Exists)
            {
                return(GetCompactTileBytes(context, path, row, col, format));
            }



            if (IsDirectoryEmpty(path))
            {
                #region On The Fly

                using (IServiceMap map = context.ServiceMap)
                {
                    ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg);

                    map.Display.SpatialReference = sRef;
                    map.Display.dpi = metadata.Dpi;

                    map.Display.iWidth  = metadata.TileWidth;
                    map.Display.iHeight = metadata.TileHeight;

                    double res = (double)scale / (metadata.Dpi / 0.0254);
                    if (map.Display.MapUnits != GeoUnits.Meters)
                    {
                        GeoUnitConverter converter = new GeoUnitConverter();
                        res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                    }

                    origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg);

                    double H = metadata.TileHeight * res;
                    double y = (orientation == GridOrientation.UpperLeft ?
                                origin.Y - H * (row + 1) :
                                origin.Y + H * row);

                    double W = metadata.TileWidth * res;
                    double x = origin.X + W * col;

                    map.Display.ZoomTo(new Envelope(x, y, x + W, y + H));
                    map.Render();

                    bool maketrans = map.Display.MakeTransparent;
                    map.Display.MakeTransparent = true;
                    MemoryStream ms = new MemoryStream();
                    map.SaveImage(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);
                    map.Display.MakeTransparent = maketrans;

                    return(ms.ToArray());
                }

                #endregion

                #region Tile from Existing UpLevel Tiles (Vorteil Resampling wird nicht von Browser erledigt, ist meistens Fast -> hier Nearstneigbor)

                int level2 = metadata.Scales.IndexOf(scale);
                if (level2 <= 0)
                {
                    return(null);
                }

                using (IServiceMap map = context.ServiceMap)
                {
                    double res = (double)scale / (metadata.Dpi / 0.0254);
                    if (map.Display.MapUnits != GeoUnits.Meters)
                    {
                        GeoUnitConverter converter = new GeoUnitConverter();
                        res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits);
                    }

                    double H = metadata.TileHeight * res;
                    double y = origin.Y - H * (row + 1);

                    double W = metadata.TileWidth * res;
                    double x = origin.X + W * col;

                    while (true)
                    {
                        if (level2 <= 0)
                        {
                            break;
                        }

                        double scale2 = metadata.Scales[level2 - 1];

                        string path2 = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" +
                                       TileServiceMetadata.ScalePath(orientation, epsg, scale2);
                        if (IsDirectoryEmpty(path2))
                        {
                            level2--;
                            continue;
                        }


                        double res2 = scale2 / (metadata.Dpi / 0.0254);

                        double W2 = metadata.TileWidth * res2;
                        double H2 = metadata.TileHeight * res2;

                        int col2_0 = (int)Math.Floor((x - origin.X) / W2);
                        int row2_0 = (int)Math.Floor((origin.Y - (y + H)) / H2);

                        int col2_1 = (int)Math.Floor((x + W - origin.X) / W2);
                        int row2_1 = (int)Math.Floor((origin.Y - y) / H2);

                        double x2_0 = origin.X + W2 * col2_0,
                               y2_0 = origin.Y - H2 * (row2_1 + 1);

                        double W20 = Math.Abs(col2_1 - col2_0 + 1) * W2,
                               H20 = Math.Abs(row2_1 - row2_0 + 1) * H2;

                        using (Bitmap bm = new Bitmap(Math.Abs(col2_1 - col2_0 + 1) * metadata.TileWidth, Math.Abs(row2_1 - row2_0 + 1) * metadata.TileHeight))
                            using (Graphics gr = Graphics.FromImage(bm))
                            {
                                for (int r2 = row2_0; r2 <= row2_1; r2++)
                                {
                                    for (int c2 = col2_0; c2 <= col2_1; c2++)
                                    {
                                        byte[] buffer = GetCompactTileBytes(context, path2, r2, c2, format);
                                        if (buffer != null && buffer.Length > 0)
                                        {
                                            MemoryStream ms        = new MemoryStream(buffer);
                                            var          tileImage = Image.FromStream(ms);
                                            gr.DrawImage(tileImage, new PointF((c2 - col2_0) * metadata.TileWidth, (r2 - row2_0) * metadata.TileHeight));
                                        }
                                    }
                                }

                                float imageX = (float)((x - x2_0) / W20 * (double)bm.Width);
                                float imageY = bm.Height - (float)((y - y2_0) / H20 * (double)bm.Height);

                                float imageW = (float)((double)metadata.TileWidth * res / res2);
                                float imageH = (float)((double)metadata.TileHeight * res / res2);

                                using (Bitmap outputBm = new Bitmap(metadata.TileWidth, metadata.TileHeight))
                                    using (Graphics outputGr = Graphics.FromImage(outputBm))
                                    {
                                        outputGr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

                                        outputGr.DrawImage(bm,
                                                           new RectangleF(-.5f, -.5f, (float)outputBm.Width + 1f, (float)outputBm.Height + 1f),
                                                           new RectangleF(imageX, imageY - imageH, imageW, imageH),
                                                           GraphicsUnit.Pixel);


                                        MemoryStream output = new MemoryStream();
                                        outputBm.Save(output, format == ".png" ? ImageFormat.Png : ImageFormat.Jpeg);

                                        return(output.ToArray());
                                    }
                            }
                    }
                }

                #endregion
            }


            return(null);
        }
Beispiel #21
0
        public void Request(IServiceRequestContext context)
        {
            if (context == null || context.ServiceRequest == null || context.ServiceMap == null)
            {
                return;
            }

            if (_mapServer == null)
            {
                context.ServiceRequest.Response = "<FATALERROR>MapServer Object is not available!</FATALERROR>";
                return;
            }

            TileServiceMetadata metadata = context.ServiceMap.MetadataProvider(_metaprovider) as TileServiceMetadata;

            if (metadata == null || metadata.Use == false)
            {
                context.ServiceRequest.Response = "<ERROR>Service is not used with Tile Service</ERROR>";
                return;
            }

            string service = context.ServiceRequest.Service;
            string request = context.ServiceRequest.Request;

            //_mapServer.Log("WMTSRequest", loggingMethod.request_detail, request);

            if (request.Contains("=")) // QueryString
            {
                QueryString queryString = new QueryString(request);
                if (queryString.HasValue("service", "wmts") && queryString.HasValue("request", "getcapabilities") && queryString.HasValue("version", "1.0.0"))
                {
                    WmtsCapabilities100(context, metadata);
                    return;
                }
            }

            string[] args = request.Split('/');

            if (args.Length == 7)
            {
                string cacheFormat = args[0].ToLower();
                if (args[1].ToLower() != "ul" &&
                    args[1].ToLower() != "ll")
                {
                    throw new ArgumentException();
                }

                int    epsg   = int.Parse(args[2]);
                string style  = args[3].ToLower();
                double scale  = GetScale(metadata, args[4]); // double.Parse(args[4].Replace(",", "."), _nhi);
                int    row    = int.Parse(args[5]);
                int    col    = int.Parse(args[6].Split('.')[0]);
                string format = ".png";
                if (args[6].ToLower().EndsWith(".jpg"))
                {
                    format = ".jpg";
                }

                byte[] imageData = null;
                if (scale > 0)
                {
                    if (cacheFormat == "compact")
                    {
                        imageData = GetCompactTile(context, metadata, epsg, scale, row, col, format, (args[1].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft));
                    }
                    else
                    {
                        imageData = GetTile(context, metadata, epsg, scale, row, col, format, (args[1].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft));
                    }

                    if (style != "default")
                    {
                        ImageProcessingFilters filter;
                        if (Enum.TryParse <ImageProcessingFilters>(style, true, out filter))
                        {
                            imageData = ImageProcessing.ApplyFilter(imageData, filter, format == ".png" ? ImageFormat.Png : ImageFormat.Jpeg);
                        }
                    }
                }

                context.ServiceRequest.Response = new MapServerResponse()
                {
                    Data        = imageData ?? _emptyPic,
                    ContentType = "image/jpg",
                    Expires     = DateTime.UtcNow.AddDays(7)
                }.ToString();
            }

            return;
        }