OPEN IV怎样修改无法打开open xml文件件

将图片转化为二进制值保存到XML文件
& //////////////////////////存&&
XmlDocument myXmlDoc =
new XmlDocument();
myXmlDoc.LoadXml("picture");
XmlElement elem =
myXmlDoc.createElement_x("image");
打开图片文件,利用该图片构造一个文件流&&
FileStream fs =
new FileStream("../../001.jpg",
FileMode.Open);
使用文件流构造一个二进制读取器将基元数据读作二进制值&&
BinaryReader br =
new BinaryReader(fs);
byte[] imageBuffer = new
byte[br.BaseStream.Length];
br.Read(imageBuffer, <span STYLE="CoLor: #,
Convert.ToInt32(br.BaseStream.Length));
string textString = System.Convert.ToBase64String(imageBuffer);
fs.Close();
br.Close();
XmlText text =
myXmlDoc.CreateTextNode(textString);
myXmlDoc.DocumentElement.AppendChild(elem);
myXmlDoc.DocumentElement.LastChild.AppendChild(text);
myXmlDoc.Save("../../docSave.xml");
///////////////////////////////读&&
int readByte = <span STYLE="CoLor: #;
int bytesToRead = <span STYLE="CoLor: #44;
XmlTextReader xmlTxtRd =
new XmlTextReader("../../docSave.xml");
FileStream fs =
new FileStream("../../002.jpg",
FileMode.Create);
BinaryWriter bw =
new BinaryWriter(fs);
byte[] base64buffer = new
byte[bytesToRead];
while (xmlTxtRd.Read())
&&&&&&&&&&&
if (xmlTxtRd.NodeType == XmlNodeType.Element &&
xmlTxtRd.Name == "image")
&&&&&&&&&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&
readByte = xmlTxtRd.ReadBase64(base64buffer,
<span STYLE="CoLor: #,
bytesToRead);
&&&&&&&&&&&&&&&&&&&
bw.Write(base64buffer, <span STYLE="CoLor: #,
readByte);
&&&&&&&&&&&&&&&
} while (bytesToRead &= readByte);
&&&&&&&&&&&
bw.Flush();
bw.Close();
fs.Close();
xmlTxtRd.Close();
把一幅图片保存到xml中去:
2:具体代码如下:
命名空间添加:
using System.X
using System.IO;
单击显示图片信息:
&protected void
btnShowImage_Click(object sender, EventArgs e)
if(upImage.PostedFile.FileName!="")
//if ("" !=upImage.PostedFile.FileName)
&&&&&&&&&&&
imagepath = upImage.PostedFile.FileN
&&&&&&&&&&&
imagesize = upImage.PostedFile.ContentLength.ToString();
&&&&&&&&&&&
imagetype = imagepath.Substring(imagepath.LastIndexOf(".") +
&&&&&&&&&&&
//判断是否是JPG或是GIF或是BMP或是PNG图片,可以任意修改图片类型,这里只是举例
&&&&&&&&&&&
if ("jpg" != imagetype && "gif" !=
imagetype && "bmp" != imagetype
&& "png" != imagetype)
&&&&&&&&&&&
&&&&&&&&&&&&&&&
Response.Write("&script
language='javascript'&alert('对不起,请选择JPG或是GIF或是BMP或是PNG图片!');&/script&");
&&&&&&&&&&&&&&&
&&&&&&&&&&&
&&&&&&&&&&&
this.Lab_imgpath.Text =
&&&&&&&&&&&
this.Lab_size.Text =
&&&&&&&&&&&
//this.ImageSmall.ImageUrl =
&&&&&&&&&&&
//this.ImageSmall.ImageUrl = Server.MapPath(imagepath);
&&&&&&&&&&&
this.ImageSmall.ImageUrl ="~/img/Winter.jpg";
&&&&&&&&&&&
Image1.ImageUrl ="~/img/Sunset.jpg";
&&&&&&&&&&&
&&&&&&&&&&&
3:单击添加图片到xml文件按钮:
protected void btnAdd_Click(object sender, EventArgs e)
其中:op_Xml():
private void OP_Xml()
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("ImageList.XML"));
XmlNode root = doc.DocumentE
string id =
Convert.ToString(Convert.ToInt32(root.LastChild.ChildNodes[0].InnerText)
string path = this.Lab_imgpath.Text.Trim();
string size = this.Lab_size.Text.Trim();
string info = this.Txt_imginfo.Text.Trim();
// 使用文件流构造一个二进制读取器将基元数据读作二进制值
FileStream fs = new FileStream(path, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] imageBuffer = new byte[br.BaseStream.Length];
br.Read(imageBuffer, 0,
Convert.ToInt32(br.BaseStream.Length));
string textString =
System.Convert.ToBase64String(imageBuffer);
fs.Close();
br.Close();
//创建元素节点
XmlNode image = doc.createElement_x("image");
XmlNode imageid = doc.createElement_x("imageID");
XmlNode imagepath = doc.createElement_x("imagepath");
XmlNode imageinfo = doc.createElement_x("imageinfo");
XmlNode imagesize = doc.createElement_x("imagesize");
XmlNode imagedata = doc.createElement_x("imagedata");
//创建文本节点
XmlNode txt_id = doc.CreateTextNode(id);
XmlNode txt_path = doc.CreateTextNode(path);
XmlNode txt_info = doc.CreateTextNode(info);
XmlNode txt_size = doc.CreateTextNode(size);
XmlNode txt_data = doc.CreateTextNode(textString);
//文本节点附加给元素节点
imageid.AppendChild(txt_id);
imagepath.AppendChild(txt_path);
imageinfo.AppendChild(txt_info);
imagesize.AppendChild(txt_size);
imagedata.AppendChild(txt_data);
//元素节点附加给image节点
image.AppendChild(imageid);
image.AppendChild(imagepath);
image.AppendChild(imageinfo);
image.AppendChild(imagesize);
image.AppendChild(imagedata);
//image节点附加给根节点
root.AppendChild(image);
doc.Save(Server.MapPath("ImageList.XML"));
this.Lab_message.Text = "图片添加成功!";
4:原始的XML文件如下:
&?xml version="1.0"
encoding="utf-8"?&
&imagelist&
&imageID&1&/imageID&
&imagepath&C:\Documents and
Settings\Administrator\My
Documents\image\新建文件夹\it1.jpg&/imagepath&
&imageinfo&图片1&/imageinfo&
&imagesize&3563&/imagesize&
&imagedata&/9j/4AAQSkZJRgABAQEASABIAAD//gApSW50ZWwoUikgSlBFRyBMaWJyYXJ5LCB2ZXJzaW9uIDEsNSw0LDM2/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAWgB4AwEiAAIRAQMRAf/EABsAAAIDAQEBAAAAAAAAAAAAAAQFAgMGAAEH/8QAPhAAAgEDAwIEBAMDCQkAAAAAAQIDAAQRBRIhMUEGEyJ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BgiiS5ZSf2CsuR6gvxrqZkcV1MDOn/9k=&/imagedata&
&/imagelist&
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。TileStache URLs are based on a Google Maps-like scheme:
/{layer name}/{zoom}/{column}/{row}.{extension}
An example tile URL might look like this:
http://example.org/path/tile.cgi/streets/12/656/1582.png
For JSON responses such as those from the , URLs
can include an optional callback for
http://example.org/path/tile.cgi/streets/12/656/1582.json?callback=funcname
Interactive, slippy-map previews of tiles are also available:
/{layer name}/preview.html
Get a type string and tile binary for a given request layer tile.
Arguments to getTile:
Instance of Core.Layer to render.
One ModestMaps.Core.Coordinate corresponding to a single tile.
Filename extension to choose response type, e.g. "png" or
ignore_cached
Optional boolean: always re-render the tile, whether it's in the cache or
not. Default False.
Return value of getTile is a tuple containing a mime-type string
such as "image/png" and a complete byte string representing the
rendered tile.
documentation for more information.
Generate a mime-type and response body for a given request. This is the function
to use when creating new HTTP interfaces to TileStache.
Arguments to requestHandler:
Required file path string for a JSON configuration file or a configuration
object with cache, layers, and dirpath
properties, such as
Required end portion of a request URL including the layer name and tile
coordinate, e.g. "/roads/12/656/1582.png".
query_string
Optional query string. Currently used only for JSONP callbacks.
script_name
Optional script name corresponds to CGI environment variable SCRIPT_NAME, used to calculate correct 302 redirects.
Return value of requestHandler is a tuple containing a mime-type string
such as "image/png" and a complete byte string representing the
rendered tile.
documentation for more information.
We currently provide three scripts for serving tiles: one for a WSGI-based
webserver, one for a CGI-based webserver, and one for Apache mod_python.
TileStache comes with a WSGI application and a
web server. To use the
built-in server, run tilestache-server.py,
which (by default) looks for a config file named tilestache.cfg
in the current directory and then serves tiles on
http://127.0.0.1:8080/. Check tilestache-server.py --help
to change these defaults.
Alternatively, any WSGI server can be pointed at an instance of
TileStache.WSGITileServer. Here’s how to use it with
$ gunicorn "TileStache:WSGITileServer('/path/to/tilestache.cfg')"
The same configuration can be served with uWSGI like so. Note the
usage of the --eval option over --module as this latter
option does not support argument passing:
$ uwsgi --http :8080 --eval 'import TileS \
application = TileStache.WSGITileServer("/path/to/tilestache.cfg")'
documentation for more information.
Using TileStache through CGI supports basic tile serving, and is useful for
simple testing and low-to-medium traffic websites. This is a complete, working
CGI script that looks for configuration in a local file called
tilestache.cfg:
#!/usr/bin/python
import os, TileStache
TileStache.cgiHandler(os.environ, 'tilestache.cfg', debug=True)
documentation for more information.
Using TileStache through mod_python improves performance by
caching imported modules, but must be configured via the Apache webserver
config. This is a complete example configuration for a webserver publishing
tiles configured by a file in /etc:
&Directory /var/www/tiles&
AddHandler mod_python .py
PythonHandler TileStache::modpythonHandler
PythonOption config /etc/tilestache.cfg
&/Directory&
documentation for more information.
TileStache configuration is stored in JSON files, and is composed of two main
top-level sections: "cache" and "layers". There are
examples of both in this minimal sample configuration:
"cache": {"name": "Test"},
"layers": {
"provider": {"name": "mapnik", "mapfile": "style.xml"},
"projection": "spherical mercator"
A Cache is the part of TileStache that stores static files to speed up future
requests. A few default caches are shown here, with additional cache classes
defined in
Jump to , ,
Simple cache that doesn’t actually cache anything.
Activity is optionally logged, though.
Example configuration:
"cache": {
"name": "Test",
"verbose": true
"layers": { … }
Test cache parameters:
Optional boolean flag to write cache activities to a logging function,
defaults to False if omitted.
documentation for more information.
Caches files to disk.
Example configuration:
"cache": {
"name": "Disk",
"path": "/tmp/stache",
"umask": "0000",
"dirs": "portable",
"gzip": ["xml", "json"]
"layers": { … }
Disk cache parameters:
Required local directory path where files should be stored.
Optional string representation of octal permission mask for stored files.
Defaults to "0022".
Optional string saying whether to create cache directories that are safe or
portable. For an example tile 12/656/1582.png,
"portable" creates matching directory trees while
"safe" guarantees directories with fewer files, e.g.
12/000/656/001/582.png. Defaults to "safe".
Optional list of file formats that should be stored in a
compressed form. Defaults to ["txt", "text", "json", "xml"].
Provide an empty list in the configuration for no compression.
If your configuration file is loaded from a remote location, e.g.
/tilestache.cfg, the path must
be an unambiguous filesystem path, e.g. "file:///tmp/cache".
documentation for more information.
Caches tiles to multiple, ordered caches.
Multi cache is well-suited for a speed-to-capacity gradient, for example a
combination of
to take advantage of the high speed of memcache and the high capacity of S3.
Each tier of caching is checked sequentially when reading from the cache, while
all tiers are used together for writing. Locks are only used with the first cache.
Example configuration:
"cache": {
"name": "Multi",
"tiers": [
"name": "Memcache",
"servers": ["127.0.0.1:11211"]
"name": "Disk",
"path": "/tmp/stache"
"layers": { … }
Multi cache parameters:
Required list of cache configurations. The fastest, most local cache should
be at the beginning of the list while the slowest or most remote cache
should be at the end. Memcache and S3 together make a great pair.
documentation for more information.
Caches tiles to ,
requires .
Example configuration:
"cache": {
"name": "Memcache",
"servers": ["127.0.0.1:11211"],
"revision": 0,
"key prefix": "unique-id"
"layers": { … }
Memcache cache parameters:
Optional array of servers, list of "{host}:{port}" pairs.
Defaults to ["127.0.0.1:11211"] if omitted.
Optional revision number for mass-expiry of cached tiles regardless of lifespan.
Defaults to 0.
key prefix
Optional string to prepend to Memcache generated key.
Useful when running multiple instances of TileStache
that share the same Memcache instance to avoid key
collisions. The key prefix will be prepended to the
key name. Defaults to "".
documentation for more information.
Caches tiles to ,
Example configuration:
"cache": {
"name": "Redis",
"host": "localhost",
"port": 6379,
"key prefix": "unique-id"
"layers": { … }
Redis cache parameters:
Defaults to "localhost" if omitted.
I Defaults to 6379 if omitted.
I Redis database number, defaults to 0 if omitted.
key prefix
Optional string to prepend to generated key.
Useful when running multiple instances of TileStache
that share the same Redis database to avoid key
collisions (though the prefered solution is to use a different
db number). The key prefix will be prepended to the
key name. Defaults to "".
documentation for more information.
Caches tiles to ,
Example configuration:
"cache": {
"name": "S3",
"bucket": "&bucket name&",
"access": "&access key&",
"secret": "&secret key&"
"reduced_redundancy": False
"layers": { … }
S3 cache parameters:
Required bucket name for S3. If it doesn’t exist, it will be created.
Optional access key ID for your S3 account. You can find this under “Security
Credentials” at your .
Optional secret access key for your S3 account. You can find this under “Security
Credentials” at your .
Optional boolean flag for whether to use the locking feature on S3.
True by default. A good reason to set this to
false would be the additional price and time required for each
lock set in S3.
Optional path under bucket to use as the cache directory. ex. 'path': 'cache' will
put tiles under {bucket}/cache/
reduced_redundancy
Optional boolean specifying whether to use Reduced Redundancy Storage mode in S3.
Files stored with RRS incur less cost but have reduced redundancy in Amazon's storage
When access or secret are not provided, the environment variables
AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY will be used.
for more information.
documentation for more information.
New caches with functionality that’s not strictly core to TileStache first appear in
LimitedDisk
Cache that stores a limited amount of data. This is an example cache that uses
a SQLite database to track sizes and last-read times for cached tiles, and
removes least-recently-used tiles whenever the total size of the cache exceeds
a set limit. See
for more information.
A Layer represents a set of tiles in TileStache. It keeps references to
providers, projections, a Configuration instance, and other details required
for to the storage and rendering of a tile set.
Example layer configuration:
"cache": …,
"example-name":
"provider": { … },
"metatile": { … },
"preview": { … },
"stale lock timeout": …,
"cache lifespan": …,
"projection": …,
"write cache": …,
"bounds": { … },
"allowed origin": …,
"maximum cache age": …,
"redirects": …,
"tile height": …,
"jpeg options": …,
"png options": …,
"pixel effect": { … }
The public-facing URL of a single tile for this layer might look like this:
/tilestache.cgi/example-name/0/0/0.png
Shared layer parameters:
Refers to a Provider, explained in detail under
Optionally makes it possible for multiple individual tiles to be rendered
at one time, for greater speed and efficiency. This is commonly used for
bitmap providers such as Mapnik. See
for more information.
Optionally overrides the starting point for the built-in per-layer slippy
map preview, useful for image-based layers where appropriate. See
for more information.
projection
Names a geographic projection, explained in
. If omitted, defaults to
"spherical mercator".
stale lock timeout
An optional number of seconds to wait before forcing a lock that might be
stuck. This is defined on a per-layer basis, rather than for an entire
cache at one time, because you may have different expectations for the
rendering speeds of different layer configurations. Defaults to
cache lifespan
An optional number of seconds that cached tiles should be stored. This is
defined on a per-layer basis. Defaults to forever if None,
0 or omitted.
write cache
An optional boolean value to allow skipping cache write altogether.
This is defined on a per-layer basis. Defaults to true if omitted.
An optional dictionary of six tile boundaries to limit the rendered area:
low (lowest zoom level), high (highest zoom level),
north, west, south, and east
(all in degrees). When any of these are omitted, default values are
north=89, west=-180, south=-89,
east=180, low=0, and high=31.
A list of dictionaries will also be accepted, indicating a set of possible
bounding boxes any one of which includes possible tiles.
allowed origin
An optional string that shows up in the response HTTP header
useful for when you need to provide javascript direct access to response
data such as GeoJSON or pixel values. The header is part of a
Pro-tip: if you want to allow maximum permissions and minimal
security headache, use a value of "*" for this.
maximum cache age
An optional number of seconds used to control behavior of downstream caches.
Causes TileStache responses to include
HTTP response headers. Useful when TileStache is itself hosted behind an HTTP
cache such as Squid, Cloudfront, or Akamai.
An optional dictionary of per-extension HTTP redirects, treated as
lowercase. Useful in cases where your tile provider can support many
formats but you want to enforce limits to save on cache usage. If a request
is made for a tile with an extension in the dictionary keys, a response can
be generated that redirects the client to the same tile with another
extension. For example, use the setting {"jpg": "png"}
to force all requests for JPEG tiles to be redirected to PNG tiles.
tile height
An optional integer gives the height of the image tile in pixels. You
almost always want to leave this at the default value of 256,
but you can use a value of 512 to create double-size,
double-resolution tiles for high-density phone screens.
jpeg options
An optional dictionary of JPEG creation options, passed through
Valid options include quality (integer), progressive
(boolean), and optimize (boolean).
png options
An optional dictionary of PNG creation options, passed through
Valid options include palette (URL or filename), palette256
(boolean) and optimize (boolean).
pixel effect
An optional dictionary that defines an effect to be applied for all tiles
of this layer. Pixel effect can be any of these: blackwhite,
greyscale, desaturate, pixelate,
halftone, or blur.
A Provider is the part of TileStache that stores static files to speed up
future requests. A few default providers are shown here, with additional
provider classes defined in
Jump to , ,
Built-in Mapnik provider, renders map images from Mapnik XML files.
Example Mapnik provider configuration:
"cache": { … }.
"provider":
"name": "mapnik",
"mapfile": "style.xml"
Mapnik provider parameters:
Required local file path to Mapnik XML file.
Optional relative directory path to *.ttf font files
for more information.
Proxy provider, to pass through and cache tiles from other places.
Example Proxy provider configuration:
"cache": { … }.
"provider":
"name": "proxy",
"url": "http://tile.openstreetmap.org/{Z}/{X}/{Y}.png"
Proxy provider parameters:
Optional URL template for remote tiles, for example:
"http://tile.openstreetmap.org/{Z}/{X}/{Y}.png"
Optional provider name string from Modest Maps built-ins. See
ModestMaps.builtinProviders.keys() for a list. Example:
"OPENSTREETMAP".
Defines a timeout in seconds for the request.
If not defined, the global default timeout setting will be used.
for more information.
Provider that returns vector representation of features in a data source.
Currently two serializations and three encodings are supported for a total
of six possible kinds of output with these tile name extensions:
GeoJSON (.geojson)
Conforms to the .
Arc GeoServices JSON (.arcjson)
Conforms to ESRI’s .
GeoBSON (.geobson) and Arc GeoServices BSON (.arcbson)
GeoJSON and Arc JSON.
GeoAMF (.geoamf) and Arc GeoServices AMF (.arcamf)
GeoJSON and Arc JSON.
Example Vector provider configurations:
"cache": { … }.
"vector-postgis-points":
"provider": {"name": "vector", "driver": "PostgreSQL",
"parameters": {"dbname": "geodata", "user": "geodata",
"table": "planet_osm_point"}}
"vector-shapefile-lines":
"provider": {"name": "vector", "driver": "shapefile",
"parameters": {"file": "oakland-uptown-line.latlon.shp"},
"properties": {"NAME": "name", "HIGHWAY": "highway"}}
"vector-sf-streets":
"provider": {"name": "vector", "driver": "GeoJSON",
"parameters": {"file": "stclines.json"},
"properties": ["STREETNAME"]}
"provider": {"name": "vector", "driver": "MySQL",
"parameters": {"dbname": "geodata", "port": "3306",
"user": "geotest", "table": "test"},
"properties": ["name"], "id_property": "oid"}
"provider": {"name": "vector", "driver": "Oracle",
"parameters": {"dbname": "ORCL", "port": "3306",
"user": "scott", "password": "tiger",
"table": "test"}}
"provider": {"name": "vector", "driver": "Spatialite",
"parameters": {"file": "test.sqlite", "layer": "test"}}
Vector provider parameters:
String used to identify an OGR driver. Currently, only
"ESRI Shapefile", "PostgreSQL", and
"GeoJSON" are supported as data source drivers, with
"postgis" and "shapefile" accepted as
synonyms. Not case-sensitive.
parameters
Dictionary of parameters for each driver.
PostgreSQL, MySQL and Oracle
"dbname" parameter is required, with name of database.
"host", "user", and "password"
are optional connection parameters. One of "table" or
"query" is required, with a table name in the first case
and a complete SQL query in the second.
Shapefile and GeoJSON
"file" parameter is required, with filesystem path to
data file.
Spatialite
"file" parameter is required, with filesystem path to
data file.
"layer" parameter is required, and is the name of
the SQLite table.
properties
Optional list or dictionary of case-sensitive output property names.
If omitted, all fields from the data source will be included in response.
If a list, treated as a whitelist of field names to include in response.
If a dictionary, treated as a whitelist and re-mapping of field names.
Default is true.
Boolean flag for optionally clipping the output geometries to the
bounds of the enclosing tile, or the string value "padded"
for clipping to the bounds of the tile plus 5%. This results in incomplete
geometries, dramatically smaller file sizes, and improves performance and
compatibility with .
Default is false.
Boolean flag for optionally returning geometries in projected rather than
geographic coordinates. Typically this means EPSG:900913 a.k.a.
spherical mercator projection. Stylistically a poor fit for GeoJSON, but
useful when returning Arc GeoServices responses.
Default is 6.
Optional number of decimal places to use for floating point values.
Optional number of tile pixels for spacing geometries in responses. Used
to cut down on the number of returned features by ensuring that only those
features at least this many pixels apart are returned. Order of features
in the data source matters: early features beat out later features.
Default is false.
Boolean flag for optionally expanding output with additional whitespace
for readability. Results in larger but more readable GeoJSON responses.
for more information.
Templated URL provider, to pass through and cache tiles from WMS servers.
Example UrlTemplate provider configuration:
"cache": { … }.
"provider":
"name": "url template",
"template": "/?bbox=$xmin,$ymin,$xmax,$ymax"
UrlTemplate provider parameters:
String with substitutions suitable for use in
The variables available for substitution are width,
height (in pixels), srs (in
xmin, ymin, xmax, ymax (in
projected map units), and zoom.
"/?bbox=$xmin,$ymin,$xmax,$ymax&bboxSR=102113&size=$width,$height&imageSR=102113&format=jpg&f=image".
Optional string with HTTP Referer URL to send to WMS server.
Some WMS servers use the Referer request header to a
this parameter provides one.
source projection
Names a geographic projection, explained in , that
coordinates should be transformed to for requests.
Defines a timeout in seconds for the request.
If not defined, the global default timeout setting will be used.
for more information.
Provider that reads stored images from .
Example MBTiles provider configuration:
"cache": { … }.
"provider":
"name": "mbtiles",
"tileset": "collection.mbtiles"
MBTiles provider parameters:
Required local file path to MBTiles tileset file, a SQLite 3 database file.
for more information.
Built-in Mapnik
renders JSON raster objects from Mapnik 2.0+.
Example Mapnik Grid provider configurations:
"cache": { … }.
"one-grid":
"provider":
"name": "mapnik grid",
"mapfile": "style.xml",
"layer_index": 1
"two-grids":
"provider":
"name": "mapnik grid",
"mapfile": "style.xml",
[2, ["population"]],
[0, ["name", "population"]]
Mapnik Grid provider parameters:
Required local file path to Mapnik XML file.
Optional array of field names to return in the response, defaults to all.
An empty list will return no field names, while a value of null
is equivalent to all.
layer_index
Optional layer from the mapfile to render, defaults to 0 (first layer).
Optional ordered list of (layer_index, fields) if provided
layers overrides both layer_index and fields
arguments.
Optional scale factor of output raster, defaults to 4 (64×64).
layer_id_key
Optional. If set, each item in the "data" property will have
its source mapnik layer name added, keyed by this value. Useful for
distingushing between data items.
for more information.
The Sandwich Provider supplies a Photoshop-like rendering pipeline, making it
possible to use the output of other configured tile layers as layers or masks
to create a combined output. Sandwich is modeled on Lars Ahlzen’s
Sandwich require the external
to function.
Example Sandwich provider configurations:
"cache": { … }.
"sandwiches":
"provider":
"name": "Sandwich",
{"src": "base"},
{"src": "outlines", "mask": "halos"},
{"src": "streets"}
"provider": {"name": "mapnik", "mapfile": "mapnik-base.xml"}
"provider": {"name": "mapnik", "mapfile": "mapnik-halos.xml"},
"metatile": {"buffer": 128}
"outlines":
"provider": {"name": "mapnik", "mapfile": "mapnik-outlines.xml"},
"metatile": {"buffer": 16}
"streets":
"provider": {"name": "mapnik", "mapfile": "mapnik-streets.xml"},
"metatile": {"buffer": 128}
Sandwich provider parameters:
Required layer or stack of layers that can be combined to create output.
The stack is a list, with solid color or raster layers from elsewhere
in the configuration, and is described in detail in the dedicated
for more information.
New providers with functionality that’s not strictly core to TileStache first appear in
Grid rendering for TileStache. UTM provider draws gridlines in tiles,
in transparent images suitable for use as map overlays. See
for more information.
PostGeoJSON
Provider that returns GeoJSON data responses from PostGIS queries. This is an
example of a provider that does not return an image, but rather queries a
database for raw data and replies with a string of GeoJSON. For example, it’s
possible to retrieve data for locations of OpenStreetMap points of interest
based on a query with a bounding box intersection. See
for more information.
SolrGeoJSON
Provider that returns GeoJSON data responses from Solr spatial queries. This is
an example of a provider that does not return an image, but rather queries a
Solr instance for raw data and replies with a string of GeoJSON. See
for more information.
Layered, composite rendering for TileStache. See
for more information.
Requests for tiles have the side effect of running
to populate
a PostGIS database of OpenStreetMap data from a remote API source. It would be
normal to use this provider outside the regular confines of a web server,
perhaps with a call to tilestache-seed.py governed by a cron job or
some other out-of-band process. See
for more information.
A Projection defines the relationship between the rendered tiles and the
underlying geographic data. Generally, just one popular projection is used for
most web maps, "spherical mercator".
Provided projections:
spherical mercator
Projection for most commonly-used web map tile scheme, equivalent to
EPSG:900913. The simplified projection used here is described
in greater detail at
Unprojected projection for the other commonly-used web map tile scheme,
equivalent to EPSG:4326.
You can define your own projection, with a module and object name as arguments:
"layer-name": {
"projection": "Module:Object",
The object must include methods that convert between coordinates, points, and
locations. See the included mercator and WGS84 implementations for example.
You can also instantiate a projection class using this syntax:
"layer-name": {
"projection": "Module:Object()"
for more information.
Metatiles are larger areas to be rendered at one time, often used because it’s
more efficient to render a large number of contiguous tiles at once than each
one separately.
Example metatile configuration:
"cache": …,
"example-name":
"provider": { … },
"metatile":
"rows": 4,
"columns": 4,
"buffer": 64
This example metatile is four rows tall and four columns wide with a buffer
of 64 pixels, for a total bitmap size of 4 × 256 + 64 × 2 = 1152.
Metatile parameters:
Height of the metatile measured in tiles.
Width of the metatile measured in tiles.
Buffer area around the metatile, measured in pixels. This is useful for
providers with labels or icons, where it’s necessary to draw a bit extra
around the edges to ensure that text is not cut off.
TileStache includes a built-in slippy map preview, that can be viewed in a
browser using the URL /{layer name}/preview.html, e.g.
http://example.org/example-name/preview.html. The settings for
this preview are completely optional, but can be set on a per-layer basis
for control over starting location and file extension.
Example preview configuration:
"cache": …,
"example-name":
"provider": { … },
"preview":
"lat": 37.80439,
"lon": -122.27127,
"zoom": 15,
"ext": "jpg"
This example preview displays JPG tiles, and is centered on
Preview parameters:
Starting latitude in degrees.
Starting longitude in degrees.
Starting zoom level.
Filename extension, e.g. "png".
TileStache supports configurable index pages for the front page of an instance.
A custom index can be specified as a filename relative to the configuration
location. Typically an HTML document would be given here, but other kinds of
files such as images can be used, with MIME content-type headers determined by
A simple text greeting is displayed if no index is provided.
Example index page configuration:
"cache": …,
"layers": …,
"index": "filename.html"
Example index page configuration using a remote image:
"cache": …,
"layers": …,
"index": "http://tilestache.org/mustaches.jpg"
TileStache includes basic support for Python’s built-in
a logging level settable in the main configuration file. Possible logging levels
include "debug", "info", "warning",
"error" and "critical", described in the
Example logging configuration:
"cache": …,
"layers": …,
"logging": "debug"
TileStache relies on
rather than inheritance for extensibility, so all guidelines for customization
below explain what methods and properties must be defined on objects for them
to be valid as providers, caches, and configurations.
Example external provider configuration:
"cache": …,
"example-name":
"provider":
"class": "Module:Classname",
"kwargs": {"frob": "yes"}
The class value is split up into module and classname, and
dynamically included. If this doesn’t work for some reason, TileStache will
fail loudly to let you know. The kwargs value is fed to the class
constructor as a dictionary of keyword args. If your defined class doesn’t
accept any of these keyword arguments, TileStache will throw an exception.
A provider must offer at least one of two methods for rendering map areas:
renderTile or renderArea. A provider must also accept
an instance of Layer as the first argument to its constructor.
Return value of both renderTile and renderArea is an
object with a save method that can accept a file-like object and
a format name, typically an instance of the PIL.Image object but
allowing for creation of providers that save text, raw data or other non-image
A minimal provider stub class:
class ProviderStub:
def __init__(self, layer):
# create a new provider for a layer
raise NotImplementedError
def renderTile(self, width, height, srs, coord):
# return an object with a PIL-like save() method for a tile
raise NotImplementedError
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
# return an object with a PIL-like save() method for an area
raise NotImplementedError
In cases where a provider generates a response that should not be cached,
renderTile and renderArea may raise the
exception in lieu of a normal response. The exception is constructed using the
intended response object, but nothing will be written to cache. This feature
might useful in cases where a full tileset is being rendered for static
hosting, and you don’t want millions of identical ocean tiles.
for more information on custom providers and
for examples of custom providers.
Draws a single tile at a time.
Arguments to renderTile:
Pixel width of tile, typically 256.
Pixel height of tile, typically 256.
Projection as Proj4 string.
"+proj=longlat +ellps=WGS84 +datum=WGS84" is an example, see
for actual values.
Coordinate object representing a single tile.
Return value of renderTile is a
or other saveable object, used like this:
provider.renderTile(…).save(file, "XML")
Draws a variably-sized area, and is used when drawing metatiles.
Non-image providers and metatiles do not mix. If your provider returns JSON,
plaintext, XML, or some other non-PIL format, implement only the
renderTile method.
Arguments to renderArea:
Pixel width of tile, typically 256.
Pixel height of tile, typically 256.
Projection as Proj4 string.
"+proj=longlat +ellps=WGS84 +datum=WGS84" is an example, see
for actual values.
Minimum x boundary of rendered area in projected coordinates.
Minimum y boundary of rendered area in projected coordinates.
Maximum x boundary of rendered area in projected coordinates.
Maximum y boundary of rendered area in projected coordinates.
Zoom level of final map. Technically this can be derived from the other
arguments, but that’s a hassle so we’ll pass it in explicitly.
Return value of renderArea is a
or other saveable object, used like this:
provider.renderArea(…).save(file, "PNG")
A provider may offer a method for custom response types,
getTypeByExtension. This method returns a tuple with two strings:
a mime-type and a format.
Arguments to getTypeByExtension:
Filename extension string, e.g. "png", "json", etc.
Example external provider configuration:
"class": "Module:Classname",
"kwargs": {"frob": "yes"}
"layers": { … }
The class value is split up into module and classname, and
dynamically included. If this doesn’t work for some reason, TileStache will
fail loudly to let you know. The kwargs value is fed to the class
constructor as a dictionary of keyword args. If your defined class doesn’t
accept any of these keyword arguments, TileStache will throw an exception.
A cache must provide all of these five methods: lock,
unlock, remove, read, and save.
Each method requires three arguments:
Instance of a layer.
Single Coordinate that represents a tile.
String like "png" or "jpg" that is used as a
filename extension.
The save method accepts an additional argument before the others:
Raw content to save to the cache.
A minimal cache stub class:
class CacheStub:
def lock(self, layer, coord, format):
# lock a tile
raise NotImplementedError
def unlock(self, layer, coord, format):
# unlock a tile
raise NotImplementedError
def remove(self, layer, coord, format):
# remove a tile
raise NotImplementedError
def read(self, layer, coord, format):
# return raw tile content from cache
raise NotImplementedError
def save(self, body, layer, coord, format):
# save raw tile content to cache
raise NotImplementedError
for more information on custom caches and
for examples of custom caches.
A complete configuration object includes cache,
layers, and dirpath properties and
optional index property:
Cache instance, e.g.
for details on what makes a usable cache.
Dictionary of layers keyed by name.
Local filesystem path for this configuration, useful for expanding relative
Two-element tuple with mime-type and content for installation index page.
When creating a custom layers dictionary, e.g. for dynamic layer
collections backed by some external configuration, these
must be provided for a complete collection of layers:
Return list of layer name strings.
Return list of (name, layer) pairs.
__contains__
Return boolean true if given key is an existing layer.
__getitem__
Return existing layer object for given key or raise KeyError.
A minimal layers dictionary stub class:
class LayersStub:
def keys(self):
# return a list of key strings
raise NotImplementedError
def items(self):
# return a list of (key, layer) tuples
raise NotImplementedError
def __contains__(self, key):
# return True if the key is here
raise NotImplementedError
def __getitem__(self, key):
# return the layer named by the key
raise NotImplementedError}

我要回帖

更多关于 open iv 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信