コード例 #1
0
def get_output_format(format_type='png'):
    """
    Output format (png или geotiff)
    """
    out = None
    if format_type == 'png':
        out = mapscript.outputFormatObj('GD/PNG'.encode('utf8'))
        out.name = 'png'
        out.mimetype = 'image/png'
        out.driver = 'AGG/PNG'
        out.extension = 'png'
        out.imagemode = mapscript.MS_IMAGEMODE_RGBA
        out.transparent = mapscript.MS_TRUE
        # out.setOption('INTERLACE', 'OFF')
        # out.setOption('QUANTIZE_FORCE', 'OFF')
        # out.setOption('QUANTIZE_DIRTHER', 'OFF')
        # out.setOption('QUANTIZE_COLORS', '256')
    elif format_type == 'geotiff':
        out = mapscript.outputFormatObj('GDAL/GTiff'.encode('utf8'),
                                        'gtiff'.encode('utf8'))
        out.name = 'GTiff'
        out.mimetype = 'image/tiff'
        out.driver = 'GDAL/GTiff'
        out.extension = 'tif'
        out.imagemode = mapscript.MS_IMAGEMODE_INT16
        out.transparent = mapscript.MS_FALSE
    return out
コード例 #2
0
ファイル: mapfile.py プロジェクト: slub/vk2-georeference
    def __addOutputFormat__(self, dictOutFormat):
        """
        Function adds a outputformat object to the mapfile.

        @param dictOutFormat: Represents a dictionary with the outputformat arguments. It should
        contains the keys:

            @param NAME:
            @param MIMETYPE:
            @param DRIVER:
            @param EXTENSION:
            @param IMAGEMODE:
            @param TRANSPARENT:
        """
        # creates a OutputFormatObject and adds the parameter to it
        if "DRIVER" in dictOutFormat:
            outFormatObj = outputFormatObj(dictOutFormat["DRIVER"])
        else:
            raise MapfileBindingInitalizationException("Missing Driver for OutputFormat Element")

        if "NAME" in dictOutFormat:
            outFormatObj.name = dictOutFormat["NAME"]
        if "MIMETYPE" in dictOutFormat:
            outFormatObj.mimetype = dictOutFormat["MIMETYPE"]
        if "EXTENSION" in dictOutFormat:
            outFormatObj.extension = dictOutFormat["EXTENSION"]
        if "IMAGEMODE" in dictOutFormat:
            outFormatObj.imagemode = dictOutFormat["IMAGEMODE"]
        if "TRANSPARENT" in dictOutFormat:
            outFormatObj.transparent = dictOutFormat["TRANSPARENT"]

        # adds the OutputFormatObject to the mapfile
        self.mapfile.appendOutputFormat(outFormatObj)
コード例 #3
0
	def __init__(self,parent,id,size):
		wx.InitAllImageHandlers()
		self.size = size
		
		#setup map object
		self.map = mapscript.mapObj()
		self.map.width = size[0]
		self.map.height = size[1]
		#self.map.setProjection('proj=latlong,ellps=WGS84')
		self.map.setProjection('proj=lcc,ellps=GRS80') 
		# set the output format 
		self.map.setOutputFormat(mapscript.outputFormatObj('GD/PNG') )
		self.map.interlace = False #PIL can't handle interlaced PNGs
		topo=mapscript.layerObj(None) 
		topo.name="topo"  
		topo.type=mapscript.MS_LAYER_RASTER  
		topo.connectiontype=mapscript.MS_RASTER  
		topo.setProjection('proj=lcc,ellps=GRS80,datum=NAD83')
		topo.status = mapscript.MS_ON    
		topo.tileindex="maps/index.shp"
		topo.tileitem="location"
		layerNum = self.map.insertLayer(topo)
		
		#fn = self.lookupTopoFilename(0)
		#self.loadRaster(fn)
		BufferedCanvas.__init__(self,parent,id)
コード例 #4
0
ファイル: mapserializer.py プロジェクト: camptocamp/Studio
def create_agg_jpg_outputformat():
    aggof = mapscript.outputFormatObj('AGG/JPEG')
    aggof.name = 'aggjpg'
    aggof.driver = 'AGG/JPEG'
    aggof.imagemode = mapscript.MS_IMAGEMODE_RGB
    aggof.mimetype = "image/jpeg"
    return aggof
コード例 #5
0
ファイル: mapserializer.py プロジェクト: camptocamp/Studio
def dict_to_outputformatobj(dict):
    ofo = mapscript.outputFormatObj(str(dict['driver']))
    ofo.name = dict['name']
    ofo.mimetype = dict['mimetype']
    ofo.imagemode = mapscriptutils.imagemodes.lookup(dict['imagemode'])
    ofo.inmapfile = mapscript.MS_TRUE
    return ofo
コード例 #6
0
def create_agg_jpg_outputformat():
    aggof = mapscript.outputFormatObj('AGG/JPEG')
    aggof.name = 'aggjpg'
    aggof.driver = 'AGG/JPEG'
    aggof.imagemode = mapscript.MS_IMAGEMODE_RGB
    aggof.mimetype = "image/jpeg"
    return aggof
コード例 #7
0
def dict_to_outputformatobj(dict):
    ofo = mapscript.outputFormatObj(str(dict['driver']))
    ofo.name = dict['name']
    ofo.mimetype = dict['mimetype']
    ofo.imagemode = mapscriptutils.imagemodes.lookup(dict['imagemode'])
    ofo.inmapfile = mapscript.MS_TRUE
    return ofo
コード例 #8
0
def SQLITEgenerateQuickLook(infileVRT, pixelSize, Bands, Scale1, Scale2,
                            Scale3):

    quickLookPath = GLOBALS['S2']['qklooks_path']
    outname = os.path.basename(infileVRT.replace('.vrt', '_test.tif'))
    bbox = get_BBOX_from_image(infileVRT, 3857)
    print bbox
    epsg = Sentinel2_functions.get_EPSG_from_VRT(infileVRT).replace(
        "EPSG:", '')
    print epsg
    mapSize = Mapserver.calculateImageSize(bbox, pixelSize)
    print mapSize
    # Create map object ##
    mapObj = Mapserver.initMap()
    mapObj.unit = mapscript.MS_METERS
    mapObj.setProjection("init=epsg:3857")
    # overwrite driver
    mapObj.outputformat = mapscript.outputFormatObj("GDAL/GTiff")
    mapObj.outputformat.name = "GTif"
    mapObj.outputformat.mimetype = "image/tiff"
    mapObj.outputformat.driver = "GDAL/GTiff"
    mapObj.outputformat.extension = "tif"
    mapObj.outputformat.setOption("COMPRESSION", "LZW")

    mapObj.setSize(int(mapSize[0]), int(mapSize[1]))
    mapObj.setExtent(float(bbox[0]), float(bbox[1]), float(bbox[2]),
                     float(bbox[3]))

    RasterLayer(mapObj, infileVRT, 'qkl', Bands, Scale1, Scale2, Scale3)

    ## Generate image file
    imgFilename = Mapserver.MapToFile(mapObj, quickLookPath, outname)
    Mapserver.WorldFile(mapObj, imgFilename)
コード例 #9
0
ファイル: mapfile.py プロジェクト: slub/vk2-georeference
    def __addOutputFormat__(self, dictOutFormat):
        """
        Function adds a outputformat object to the mapfile.

        @param dictOutFormat: Represents a dictionary with the outputformat arguments. It should
        contains the keys:

            @param NAME:
            @param MIMETYPE:
            @param DRIVER:
            @param EXTENSION:
            @param IMAGEMODE:
            @param TRANSPARENT:
        """
        # creates a OutputFormatObject and adds the parameter to it
        if "DRIVER" in dictOutFormat:
            outFormatObj = outputFormatObj(dictOutFormat["DRIVER"])
        else:
            raise MapfileBindingInitalizationException(
                "Missing Driver for OutputFormat Element")

        if "NAME" in dictOutFormat:
            outFormatObj.name = dictOutFormat["NAME"]
        if "MIMETYPE" in dictOutFormat:
            outFormatObj.mimetype = dictOutFormat["MIMETYPE"]
        if "EXTENSION" in dictOutFormat:
            outFormatObj.extension = dictOutFormat["EXTENSION"]
        if "IMAGEMODE" in dictOutFormat:
            outFormatObj.imagemode = dictOutFormat["IMAGEMODE"]
        if "TRANSPARENT" in dictOutFormat:
            outFormatObj.transparent = dictOutFormat["TRANSPARENT"]

        # adds the OutputFormatObject to the mapfile
        self.mapfile.appendOutputFormat(outFormatObj)
コード例 #10
0
 def testSetRGBAImage(self):
     """set image of new symbolObj"""
     assert self.x_symbol.name == 'xmarks'
     assert self.x_symbol.type == mapscript.MS_SYMBOL_PIXMAP
     format = mapscript.outputFormatObj('AGG/PNG')
     img = self.x_symbol.getImage(format)
     img.save('set-%s.%s' % (self.x_symbol.name, img.format.extension))
コード例 #11
0
 def testSetPCTImage(self):
     """set image of new symbolObj"""
     assert self.h_symbol.name == 'house'
     assert self.h_symbol.type == mapscript.MS_SYMBOL_PIXMAP
     format = mapscript.outputFormatObj('AGG/PNG')
     format.transparent = mapscript.MS_ON
     img = self.h_symbol.getImage(format)
     img.save('set-%s.%s' % (self.h_symbol.name, img.format.extension))
コード例 #12
0
 def xtestConstructorImage(self):
     """create new instance of symbolObj from an image"""
     symbol = mapscript.symbolObj('xmarks', XMARKS_IMAGE)
     assert symbol.name == 'xmarks'
     assert symbol.type == mapscript.MS_SYMBOL_VECTOR  # was MS_SYMBOL_PIXMAP!
     format = mapscript.outputFormatObj('AGG/PNG')
     img = symbol.getImage(format)
     img.save('sym-%s.%s' % (symbol.name, img.format.extension))
コード例 #13
0
 def testConstructorWithFormat(self):
     """imageObj with an optional driver works"""
     driver = 'AGG/PNG'
     format = mapscript.outputFormatObj(driver)
     imgobj = mapscript.imageObj(10, 10, format)
     assert imgobj.thisown == 1
     assert imgobj.format.driver == driver
     assert imgobj.height == 10
     assert imgobj.width == 10
コード例 #14
0
ファイル: image_test.py プロジェクト: dmorissette/mapserver
 def testConstructorWithFormat(self):
     """imageObj with an optional driver works"""
     driver = 'AGG/PNG'
     format = mapscript.outputFormatObj(driver)
     imgobj = mapscript.imageObj(10, 10, format)
     assert imgobj.thisown == 1
     assert imgobj.format.driver == driver
     assert imgobj.height == 10
     assert imgobj.width == 10
コード例 #15
0
 def testAppendNewOutputFormat(self):
     """test that a new output format can be created on-the-fly"""
     num = self.map.numoutputformats
     new_format = mapscript.outputFormatObj('GDAL/GTiff', 'gtiffx')
     # assert new_format.refcount == 1, new_format.refcount
     self.map.appendOutputFormat(new_format)
     assert self.map.numoutputformats == num + 1
     # assert new_format.refcount == 2, new_format.refcount
     self.map.selectOutputFormat('gtiffx')
     self.map.save('testAppendNewOutputFormat.map')
     self.map.getLayerByName('INLINE-PIXMAP-RGBA').status = mapscript.MS_ON
     imgobj = self.map.draw()
     filename = 'testAppendNewOutputFormat.tif'
     imgobj.save(filename)
コード例 #16
0
 def testRemoveOutputFormat(self):
     """testRemoveOutputFormat may fail depending on GD options"""
     num = self.map.numoutputformats
     new_format = mapscript.outputFormatObj('GDAL/GTiff', 'gtiffx')
     self.map.appendOutputFormat(new_format)
     assert self.map.numoutputformats == num + 1
     # assert new_format.refcount == 2, new_format.refcount
     assert self.map.removeOutputFormat('gtiffx') == mapscript.MS_SUCCESS
     # assert new_format.refcount == 1, new_format.refcount
     assert self.map.numoutputformats == num
     self.assertRaises(mapscript.MapServerError,
                       self.map.selectOutputFormat, 'gtiffx')
     self.map.selectOutputFormat('GTiff')
     assert self.map.outputformat.mimetype == 'image/tiff'
コード例 #17
0
 def testRemoveOutputFormat(self):
     """testRemoveOutputFormat may fail depending on GD options"""
     num = self.map.numoutputformats
     new_format = mapscript.outputFormatObj('GDAL/GTiff', 'gtiffx')
     self.map.appendOutputFormat(new_format)
     assert self.map.numoutputformats == num + 1
     # assert new_format.refcount == 2, new_format.refcount
     assert self.map.removeOutputFormat('gtiffx') == mapscript.MS_SUCCESS
     # assert new_format.refcount == 1, new_format.refcount
     assert self.map.numoutputformats == num
     self.assertRaises(mapscript.MapServerError,
                       self.map.selectOutputFormat, 'gtiffx')
     self.map.selectOutputFormat('GTiff')
     assert self.map.outputformat.mimetype == 'image/tiff'
コード例 #18
0
 def testAppendNewOutputFormat(self):
     """test that a new output format can be created on-the-fly"""
     num = self.map.numoutputformats
     new_format = mapscript.outputFormatObj('GDAL/GTiff', 'gtiffx')
     # assert new_format.refcount == 1, new_format.refcount
     self.map.appendOutputFormat(new_format)
     assert self.map.numoutputformats == num + 1
     # assert new_format.refcount == 2, new_format.refcount
     self.map.selectOutputFormat('gtiffx')
     self.map.save('testAppendNewOutputFormat.map')
     self.map.getLayerByName('INLINE-PIXMAP-RGBA').status = mapscript.MS_ON
     imgobj = self.map.draw()
     filename = 'testAppendNewOutputFormat.tif'
     imgobj.save(filename)
コード例 #19
0
ファイル: mra.py プロジェクト: neogeo-technologies/mra
def outputformat(
        driver, name, mimetype=None, imagemode=None,
        extension=None, transparent=mapscript.MS_OFF, options=None):
    _format = mapscript.outputFormatObj(driver, name)

    if mimetype:
        _format.mimetype = mimetype
    if imagemode:
        _format.imagemode = imagemode
    if extension:
        _format.extension = extension
    if transparent:
        _format.transparent = transparent
    if options:
        for k, v in options.items():
            _format.setOption(k, v)
    return _format
コード例 #20
0
def outputformat(
        driver, name, mimetype=None, imagemode=None,
        extension=None, transparent=mapscript.MS_OFF, options=None):
    _format = mapscript.outputFormatObj(driver, name)

    if mimetype:
        _format.mimetype = mimetype
    if imagemode:
        _format.imagemode = imagemode
    if extension:
        _format.extension = extension
    if transparent:
        _format.transparent = transparent
    if options:
        for k, v in list(options.items()):
            _format.setOption(k, v)
    return _format
コード例 #21
0
def initMap():
    """ Initialize a generic mapObj item """
    #from datetime import datetime

    mapObj = mapscript.mapObj()
    # mapObj.debug = 5
    # mapObj.setConfigOption("MS_ERRORFILE", GLOBALS['S2']['root_path']+"S2_scripts/ms_error.txt")
    #mapObj.name = 'map_'+datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
    mapObj.name = 'Sentinel2_map'
    mapObj.transparent = mapscript.MS_TRUE
    mapObj.imagecolor = mapscript.colorObj(0, 0, 0)
    mapObj.maxsize = 2500

    # mapObj.outputformat=mapscript.outputFormatObj("GD/JPEG")
    # mapObj.outputformat.mimetype="image/jpeg;"
    # mapObj.outputformat.name="JPEG"
    # mapObj.outputformat.driver="GD/JPEG"
    # mapObj.outputformat.extension="jpg"
    # mapObj.outputformat.setOption("QUALITY","90")
    # mapObj.outputformat.transparent = mapscript.MS_TRUE
    # mapObj.outputformat.imagemode= mapscript.MS_IMAGEMODE_RGBA

    mapObj.outputformat = mapscript.outputFormatObj("AGG/PNG")
    mapObj.outputformat.name = "PNG"
    mapObj.outputformat.mimetype = "image/png"
    mapObj.outputformat.driver = "AGG/PNG"
    mapObj.outputformat.extension = "png"
    mapObj.outputformat.setOption("COMPRESSION", "7")
    mapObj.outputformat.setOption("QUANTIZE_FORCE", "ON")
    mapObj.outputformat.transparent = mapscript.MS_TRUE
    mapObj.outputformat.imagemode = mapscript.MS_IMAGEMODE_RGBA

    # WMS

    mapObj.web.metadata.set('wms_title', 'Public API for Sentinel2 imagery')
    mapObj.web.metadata.set('wms_onlineresource',
                            GLOBALS['mapserver_url'] + "wms_sentinel2.py?")
    #mapObj.web.metadata.set("wms_feature_info_mime_type","text/html")
    #webObj.metadata.set('wms_onlineresource','http://cidportal.jrc.ec.europa.eu/forobsdev/cgi-bin/mapserv?')
    mapObj.web.metadata.set('wms_enable_request', "*")
    mapObj.web.metadata.set('wms_srs', "EPSG:3857")
    mapObj.web.metadata.set('wms_abstract',
                            "WMS serving Sentinel 2 full resolution imagery")

    return mapObj
コード例 #22
0
ファイル: mapSettings.py プロジェクト: yjacolin/MapfileEditor
    def saveOutputFormatForm(self):
        self.QMapSettingWindow.mf_outputformat_message.setText("")
        ofName = str(self.QMapSettingWindow.mf_outputformat_name.text())
        ofObj = mapscript.outputFormatObj(str(self.QMapSettingWindow.mf_outputformat_driver.currentText()), ofName)
        
        if(self.QMapSettingWindow.mf_outputformat_transparent_on.isChecked() == True):
           ofObj.transparent = mapscript.MS_ON
        elif(self.QMapSettingWindow.mf_outputformat_transparent_off.isChecked() == True):
           ofObj.transparent = mapscript.MS_OFF
        ofObj.setExtension(str(self.QMapSettingWindow.mf_outputformat_extension.text()))

        ofObj.imagemode = self.imageMode[str(self.QMapSettingWindow.mf_outputformat_imagemode.currentText())]
        ofObj.setMimetype(str(self.QMapSettingWindow.mf_outputformat_mimetype.text()))

        for index in range(0, self.QMapSettingWindow.mf_outputformat_formatoptions_list.model().rowCount()):
            name = str(self.QMapSettingWindow.mf_outputformat_formatoptions_list.model().item(index, 0).text())
	    value = str(self.QMapSettingWindow.mf_outputformat_formatoptions_list.model().item(index, 1).text())

            ofObj.setOption(name, value)

        self.tmp['outputformat'][ofName] = ofObj
        self.resetOutputFormatForm()
        self.updateOutputformatList()
コード例 #23
0
ファイル: ows.py プロジェクト: cbertelli/GisClient-3
import mapscript
mapobj=mapscript.mapObj()
outputFormat=mapscript.outputFormatObj("GD/PNG")
outputFormat.name="png24"
outputFormat.setMimetype("image/png")
outputFormat.imagemode=1
outputFormat.setExtension("png")
mapobj.legend.status=1
mapobj.legend.keysizex=100
mapobj.legend.keysizey=30
mapobj.legend.keyspacingy=20
mapobj.legend.width=100
mapobj.setSize(600,1200)
mapobj.setExtent(132771,447652,134477,451064)
mapobj.setOutputFormat(outputFormat)
style=mapscript.styleObj()
style.symbolname="point5"
style.color=mapscript.colorObj(225,0,0)
cls=mapscript.classObj()
cls.insertStyle(style)
cls.name="testclass"
cls.setExpression("(4 + 4)")
mapobj.setSymbolSet('test_symbols.set')







コード例 #24
0
ファイル: gml2gtiff.py プロジェクト: DREAM-ODA-OS/eoxserver
    # create new layer
    layer = layerObj(map)
    layer.name = coverageid
    layer.data = options.output
    layer.status = MS_ON
    layer.type = MS_LAYER_RASTER
    layer.setProjection("init=epsg:%d" % epsg)
    layer.setMetaData("wcs_srs", "epsg:%d" % epsg)
    layer.setMetaData("wcs_extent", extent)
    layer.setMetaData("wcs_size", "%d %d" % (width, height))
    layer.setMetaData("wcs_default_format", "application/gml+xml")
    
    # set band metadata
    layer.setMetaData("wcs_bandcount", str(len(bands)))
    layer.setMetaData("wcs_band_names", " ".join([band['band_name'] for band in bands]))
    for band in bands:
        for key, value in band.iteritems():
            if value is None or key == "band_name":
                continue
            layer.setMetaData("%s_%s" % (band['band_name'], key), str(value))
    
    # append GML outputformat
    format = outputFormatObj("GDAL/GTiff", "GML")
    format.setExtension("xml")
    format.setMimetype("application/gml+xml")
    format.imagemode = MS_IMAGEMODE_FLOAT32
    map.appendOutputFormat(format)

    #save the map to the disk
    map.save(options.map)
コード例 #25
0
    def test_get_productlayer(self):
        #import StringIO
        import mapscript
        # getparams = web.input()

        #getparams = {'STYLES': u'', 'productcode': u'vgt-ndvi', 'legendid': u'7', 'SERVICE': u'WMS', 'subproductcode': u'ndv', 'CRS': u'EPSG:4326', 'FORMAT': u'image/png', 'REQUEST': u'GetMap', 'HEIGHT': u'1010', 'WIDTH': u'998', 'VERSION': u'1.3.0', 'productversion': u'sv2-pv2.1', 'date': u'20130221', 'mapsetcode': u'SPOTV-Africa-1km', 'TRANSPARENT': u'false', 'BBOX': u'-16.17,16.17,-15.47,16.87'}
        getparams = {'STYLES': u'',
                     'productcode': u'vgt-fapar',
                     'legendid': u'99',
                     'SERVICE': u'WMS',
                     'subproductcode': u'fapar',
                     'CRS': u'EPSG:4326',
                     'FORMAT': u'image/png',
                     'REQUEST': u'GetMap',
                     'HEIGHT': u'1010',
                     'WIDTH': u'998',
                     'VERSION': u'1.3.0',
                     'productversion': u'V1.4',
                     'date': u'20130221',
                     'mapsetcode': u'SPOTV-Africa-1km',
                     'TRANSPARENT': u'false',
                     'BBOX': u'15.46875, -17.578125, 16.171875, -16.875'}

        #getparams = {'STYLES': u'', 'productcode': u'vgt-ndvi', 'legendid': u'7', 'SERVICE': u'WMS', 'subproductcode': u'ndv', 'CRS': u'EPSG:4326', 'FORMAT': u'image/png', 'REQUEST': u'GetMap', 'HEIGHT': u'1091', 'WIDTH': u'998', 'VERSION': u'1.3.0', 'productversion': u'sv2-pv2.1', 'date': u'20130221', 'mapsetcode': u'SPOTV-Africa-1km', 'TRANSPARENT': u'false', 'BBOX': u'-25.70957541665903,9.276714800828785,-13.723491432284028,20.021343707078785'}
        # getparams = [
        #     SERVICE:'WMS',
        #     VERSION='1.3.0',
        #     REQUEST='GetMap',
        #     FORMAT='image/png',
        #     TRANSPARENT='false',
        #     productcode='vgt-ndvi',
        #     productversion='sv2-pv2.1',
        #     subproductcode='ndv',
        #     mapsetcode='SPOTV-Africa-1km',
        #     legendid='7',
        #     date='20130221',
        #     CRS='EPSG:4326'',
        #     STYLES=''
        #     WIDTH='998',
        #     HEIGHT='1010',
        #     BBOX='-26,-35,60,38'
        # ]
        p = Product(product_code=getparams['productcode'], version=getparams['productversion'])
        dataset = p.get_dataset(mapset=getparams['mapsetcode'], sub_product_code=getparams['subproductcode'])
        # print dataset.fullpath

        if hasattr(getparams, "date"):
            filedate = getparams['date']
        else:
            dataset.get_filenames()
            lastdate = dataset.get_dates()[-1].strftime("%Y%m%d")
            filedate = lastdate

        if dataset.no_year():
            filedate=dataset.strip_year(filedate)
        # lastdate = lastdate.replace("-", "")
        # mydate=lastdate.strftime("%Y%m%d")

        filename = functions.set_path_filename(filedate,
                                               getparams['productcode'],
                                               getparams['subproductcode'],
                                               getparams['mapsetcode'],
                                               getparams['productversion'],
                                               '.tif')
        productfile = dataset.fullpath + filename
        # print productfile

        #web.header('Content-type', 'image/png')
        #web.header('Content-transfer-encoding', 'binary')
        #buf = StringIO.StringIO()
        #mapscript.msIO_installStdoutToBuffer()
        #map = mapserver.getmap()
        ##map.save to a file fname.png
        ##web.header('Content-Disposition', 'attachment; filename="fname.png"')
        #contents = buf.getvalue()
        #return contents

        #logger.debug("MapServer: Installing stdout to buffer.")
        mapscript.msIO_installStdoutToBuffer()

        # projlib = "/usr/share/proj/"
        projlib = es_constants.proj4_lib_dir
        # errorfile = es_constants.apps_dir+"/analysis/ms_tmp/ms_errors.log"
        errorfile = es_constants.log_dir+"/mapserver_error.log"
        # imagepath = es_constants.apps_dir+"/analysis/ms_tmp/"

        owsrequest = mapscript.OWSRequest()

        inputparams = getparams # web.input()
        for k, v in inputparams.iteritems():
            print k + ':' + v
            owsrequest.setParameter(k.upper(), v)

        # print owsrequest

        filenamenoextention = functions.set_path_filename(filedate,
                                               getparams['productcode'],
                                               getparams['subproductcode'],
                                               getparams['mapsetcode'],
                                               getparams['productversion'],
                                               '')
        owsrequest.setParameter("LAYERS", filenamenoextention)

        productmap = mapscript.mapObj(es_constants.template_mapfile)
        productmap.setConfigOption("PROJ_LIB", projlib)
        productmap.setConfigOption("MS_ERRORFILE", errorfile)
        productmap.maxsize = 4096

        outputformat_png = mapscript.outputFormatObj('GD/PNG', 'png')
        outputformat_png.setOption("INTERLACE", "OFF")
        productmap.appendOutputFormat(outputformat_png)
        #outputformat_gd = mapscript.outputFormatObj('GD/GIF', 'gif')
        #productmap.appendOutputFormat(outputformat_gd)
        productmap.selectOutputFormat('png')
        productmap.debug = mapscript.MS_TRUE
        productmap.status = mapscript.MS_ON
        productmap.units = mapscript.MS_DD

        coords = map(float, inputparams['BBOX'].split(","))
        print coords
        llx = coords[0]
        lly = coords[1]
        urx = coords[2]
        ury = coords[3]
        print llx, lly, urx, ury

        productmap.setExtent(llx, lly, urx, ury)   # -26, -35, 60, 38
        # productmap.setExtent(-26, -35, 60, 38)

        # epsg must be in lowercase because in unix/linux systems the proj filenames are lowercase!
        # epsg = "+init=epsg:3857"
        # epsg = "+init=" + inputparams.CRS.lower()   # CRS = "EPSG:4326"
        epsg = inputparams['CRS'].lower()   # CRS = "EPSG:4326"
        productmap.setProjection(epsg)

        w = int(inputparams['WIDTH'])
        h = int(inputparams['HEIGHT'])
        productmap.setSize(w, h)

        # General web service information
        productmap.setMetaData("WMS_TITLE", "Product description")
        productmap.setMetaData("WMS_SRS", inputparams['CRS'].lower())
        # productmap.setMetaData("WMS_SRS", "epsg:3857")
        productmap.setMetaData("WMS_ABSTRACT", "A Web Map Service returning eStation2 raster layers.")
        productmap.setMetaData("WMS_ENABLE_REQUEST", "*")   # necessary!!

        product_info = querydb.get_product_out_info(productcode=inputparams['productcode'],
                                                    subproductcode=inputparams['subproductcode'],
                                                    version=inputparams['productversion'])
        if hasattr(product_info, "__len__") and product_info.__len__() > 0:
            for row in product_info:
                scale_factor = row.scale_factor
                scale_offset = row.scale_offset
                nodata = row.nodata

        legend_info = querydb.get_legend_info(legendid=inputparams['legendid'])
        if hasattr(legend_info, "__len__") and legend_info.__len__() > 0:
            for row in legend_info:
                minstep = int((row.min_value - scale_offset)/scale_factor)    #int(row.min_value*scale_factor+scale_offset)
                maxstep = int((row.max_value - scale_offset)/scale_factor)    # int(row.max_value*scale_factor+scale_offset)
                realminstep = int((row.realminstep - scale_offset)/scale_factor)
                realmaxstep = int((row.realmaxstep - scale_offset)/scale_factor)
                minstepwidth = int((row.minstepwidth - scale_offset)/scale_factor)
                maxstepwidth = int((row.maxstepwidth - scale_offset)/scale_factor)
                totwidth = int((row.totwidth - scale_offset)/scale_factor)
                totsteps = row.totsteps

            # maxstep = 255
            processing_scale = 'SCALE='+str(minstep)+','+str(maxstep)  # min(legend_step.from_step) max(legend_step.to_step) example: 'SCALE=-7000,10000'

            minbuckets = 256
            maxbuckets = 10000
            num_buckets = maxbuckets
            if minstepwidth > 0:
                num_buckets = round(totwidth / minstepwidth, 0)

            if num_buckets < minbuckets:
                num_buckets = minbuckets
            elif num_buckets > maxbuckets:
                num_buckets = 0

            # num_buckets = 10000
            if num_buckets > 0:
                processing_buckets = 'SCALE_BUCKETS='+str(num_buckets)

            # nodata = -32768     # get this value from the table products.product
            processing_novalue = ''
            if nodata is not None and minstep <= nodata < maxstep:
                processing_novalue = 'NODATA='+str(nodata)

            layer = mapscript.layerObj(productmap)
            layer.name = filenamenoextention
            layer.type = mapscript.MS_LAYER_RASTER
            layer.status = mapscript.MS_ON     # MS_DEFAULT
            layer.data = productfile
            # layer.setProjection("+init=epsg:4326")
            layer.setProjection("epsg:4326")
            layer.dump = mapscript.MS_TRUE

            # scale & buckets
            if num_buckets > 0:
                layer.setProcessing(processing_scale)
                layer.setProcessing(processing_buckets)

            if processing_novalue != '':
                layer.setProcessing(processing_novalue)

            legend_steps = querydb.get_legend_steps(legendid=inputparams['legendid'])
            if hasattr(legend_steps, "__len__") and legend_steps.__len__() > 0:
                stepcount = 0
                for step in legend_steps:
                    stepcount += 1
                    min_step = int((step.from_step - scale_offset)/scale_factor)
                    max_step = int((step.to_step - scale_offset)/scale_factor)
                    colors = map(int, (color.strip() for color in step.color_rgb.split(" ") if color.strip()))

                    if stepcount == legend_steps.__len__():    # For the last step use <= max_step
                        expression_string = '([pixel] >= '+str(min_step)+' and [pixel] <= '+str(max_step)+')'
                    else:
                        expression_string = '([pixel] >= '+str(min_step)+' and [pixel] < '+str(max_step)+')'
                    # define class object and style
                    layerclass = mapscript.classObj(layer)
                    layerclass.name = layer.name+'_'+str(stepcount)
                    layerclass.setExpression(expression_string)
                    style = mapscript.styleObj(layerclass)
                    style.color.setRGB(colors[0], colors[1], colors[2])

        result_map_file = es_constants.apps_dir+'/analysis/MAP_result.map'
        # if os.path.isfile(result_map_file):
        #     os.remove(result_map_file)
        productmap.save(result_map_file)
        image = productmap.draw()
        image.save(es_constants.apps_dir+'/analysis/'+filenamenoextention+'.png')

        contents = productmap.OWSDispatch(owsrequest)
        content_type = mapscript.msIO_stripStdoutBufferContentType()
        content = mapscript.msIO_getStdoutBufferBytes()
        #web.header = "Content-Type","%s; charset=utf-8"%content_type
        # web.header('Content-type', 'image/png')
        #web.header('Content-transfer-encoding', 'binary')
        # return content

        self.assertEquals(True, True)
コード例 #26
0
ファイル: mapserver.py プロジェクト: pcecconi/mapground
def create_mapfile(data, save=True):
    mapa = mapscript.mapObj()
    mapa.name = 'mapa_' + unicode(data['idMapa'])

    try:
        if data['imageColor']['type'] == 'hex':
            mapa.imagecolor.setHex(data['imageColor']['color'])
        else:
            mapa.imagecolor.setRGB(*(data['imageColor']['color']))
    except:
        mapa.imagecolor.setHex(MAPA_DEFAULT_IMAGECOLOR)

    mapa.setSymbolSet(MAPA_SYMBOLSET_FILENAME)
    mapa.setFontSet(MAPA_FONTSET_FILENAME)
    mapa.shapepath = MAPA_DATA_PATH

    mapa.outputformat.transparent = True

    # if data['srs']!='':
    print "mapserver: Seteando proyeccion para el mapa: %s" % data['srs']
    mapa.setProjection(data['srs'])
    # else:
    #    print "mapserver: Seteando proyeccion para el mapa: epsg:%s"%data['srid']
    #    mapa.setProjection('epsg:%s' % (data['srid']))

    if data['srid'] == '4326':
        mapa.units = mapscript.MS_DD
    else:
        mapa.units = mapscript.MS_METERS

    mapa.legend.updateFromString('LEGEND\n  KEYSIZE 20 10\n  KEYSPACING 5 5\n  LABEL\n    SIZE 10\n    OFFSET 0 0\n    SHADOWSIZE 1 1\n    TYPE TRUETYPE\n  FONT "Swz721lc"\nEND # LABEL\n  STATUS OFF\nEND # LEGEND\n\n')
    # primero seteamos extent, luego size. sino hay un comportamiento extranio y el extent no se respeta, quizas para igualar relaciones de aspecto entre ambos
    try:
        mapa.setExtent(*(data['mapFullExtent']))  # si tiene un extent overrideado
    except:
        if data['mapType'] in ('user', 'public_layers'):  # en estos casos no los calculamos
            mapa.setExtent(*(MAPA_DEFAULT_EXTENT))
        else:
            try:
                mapa.setExtent(*(data['mapBoundingBox']))
            except:
                mapa.setExtent(*(MAPA_DEFAULT_EXTENT))
    try:
        mapa.setSize(*(data['mapSize']))
    except:
        mapa.setSize(*(MAPA_DEFAULT_SIZE))

    output_geojson = mapscript.outputFormatObj('OGR/GEOJSON', 'GeoJson')
    output_geojson.setMimetype('application/json; subtype=geojson')
    output_geojson.setOption('STORAGE', 'stream')
    output_geojson.setOption('FORM', 'SIMPLE')
    mapa.appendOutputFormat(output_geojson)

    output_shapefile = mapscript.outputFormatObj('OGR/ESRI Shapefile', 'ShapeZip')
    output_shapefile.setMimetype('application/shapefile')
    output_shapefile.setOption('STORAGE', 'filesystem')
    output_shapefile.setOption('FORM', 'zip')
    output_shapefile.setOption('FILENAME', data['fileName'] + '.zip')
    mapa.appendOutputFormat(output_shapefile)

    output_csv = mapscript.outputFormatObj('OGR/CSV', 'CSV')
    output_csv.setMimetype('text/csv')
    # output_csv.setOption('LCO:GEOMETRY', 'AS_WKT')
    output_csv.setOption('STORAGE', 'filesystem')
    output_csv.setOption('FORM', 'simple')
    output_csv.setOption('FILENAME', data['fileName'] + '.csv')
    mapa.appendOutputFormat(output_csv)

    mapa.setConfigOption('MS_ERRORFILE', MAPA_ERRORFILE)
    mapa.setConfigOption('PROJ_LIB', settings.PROJ_LIB)
    mapa.setConfigOption('MS_OPENLAYERS_JS_URL', settings.MS_OPENLAYERS_JS_URL)

    mapa.legend.template = 'templates/legend.html'  # TODO: general o solo WMS?
    # mapa.web.validation.set('TEMPLATE', '[a-z/.]+') # TODO: general o solo WMS?
    mapa.web.template = 'templates/mapa-interactivo.html'  # TODO: general o solo WMS?

    mapa.web.imagepath = settings.MAP_WEB_IMAGEPATH
    mapa.web.imageurl = settings.MAP_WEB_IMAGEURL

    try:
        for k, v in data['metadata'].iteritems():
            mapa.setMetaData(k, v)
    except:
        pass  # No metadata

    # try:
    for layer_def in data['layers']:
        # print(layer_def)
        # La capa tiene Time Index (WMS-T)
        if layer_def.get('timeIndexData', None) is not None:
            mapa.insertLayer(create_tile_index_layer(layer_def))            
        mapa.insertLayer(create_ms_layer(layer_def))
    # except Exception, e:
    #     print "Failed to insert layers on mapfile: %s"%str(e)

    if save:
        mapa.save(os.path.join(settings.MAPAS_PATH, data['idMapa'] + '.map'))
        print "......mapa guardado %s" % (data['idMapa'] + '.map')

    return mapa
コード例 #27
0
ファイル: amn_map.py プロジェクト: Ecotrust-Canada/terratruth
    def createMapImage(self):
        import settings
        # Create a map object
        outputMap = mapscript.mapObj(settings.PRIVATE_MAPFILE)
        gd =  mapscript.outputFormatObj('AGG/PNG')
        outputMap.setOutputFormat(gd)
        extent = self.fields['oldata']['extent']
        outputMap.setExtent(extent['left'], extent['bottom'], extent['right'], extent['top'])
        outputMap.setSize(self.W,self.H)
        
        # Set all the layers initially off.
        i=0
        layer = outputMap.getLayer(i)
        while layer:
            layer.status = mapscript.MS_OFF
            i = i + 1
            layer = outputMap.getLayer(i)
        
        connection = "user=%s dbname=%s host=%s password=%s" % (
                            settings.DATABASE_USER,
                            settings.DATABASE_NAME,
                            (settings.DATABASE_HOST or "localhost"),
                            settings.DATABASE_PASSWORD
                        )

        # Example for WMS layer building
        layers = self.fields['oldata']['mapLayers']
        layerNames = ""
        for i,layer in enumerate(layers):
            subLayers = layer['params']['LAYERS']
            if subLayers and (type(subLayers) != types.ListType):
                subLayers = list(subLayers)
            for subLayer in subLayers:
                mapFileLayer = outputMap.getLayerByName(subLayer)
                
                # use layer from mapfile directly.
                if mapFileLayer:
                    # authenticate db connections.
                    if "user=%s" % settings.DATABASE_USER in mapFileLayer.connection:
                        mapFileLayer.connection = connection
                        mapFileLayer.status = mapscript.MS_DEFAULT
                    outputMap.insertLayer(mapFileLayer)
                # generate a custom layer dynamically.
                else:
                    wmsLayer = mapscript.layerObj()
                    wmsLayer.name = 'wms'+str(i)
                    wmsLayer.connection = layer['url'].replace("..",settings.HOST)
                    wmsLayer.connectiontype = mapscript.MS_WMS
                    wmsLayer.status = mapscript.MS_DEFAULT
                    wmsLayer.type = mapscript.MS_LAYER_RASTER
                    #wmsLayer.setProjection("init="+layer['params']['SRS'])
                    # By default take the first 'list' of any values
                    wmsLayer.metadata.set("wms_name", subLayer)
                    wmsLayer.metadata.set("wms_exceptions_format", "application/vnd.ogc.se_xml")
                    wmsLayer.metadata.set("wms_format", "image/png") #layer['params']['FORMAT'])
                    wmsLayer.metadata.set("wms_srs", layer['params']['SRS'])
                    wmsLayer.metadata.set("wms_server_version", layer['params']['VERSION'])
                    outputMap.insertLayer(wmsLayer)
                                    
        vectorLayers = self.fields['oldata']['vectorLayers']
        if len(vectorLayers) > 0:
            dataString = "poly from (select id, poly from referrals_referralshape where "
            for i,vectorLayer in enumerate(vectorLayers):
                if i == 0:
                    dataString = dataString + "id=" + str(vectorLayer)
                else:
                    dataString = dataString + " OR id=" + str(vectorLayer)
            dataString = dataString + ") as foo using unique id using SRID=3005"
            userShapeLayer = outputMap.getLayerByName("user_shapes")
            userShapeLayer.connection = connection
            userShapeLayer.status = mapscript.MS_DEFAULT
            outputMap.insertLayer(userShapeLayer)
            userShapeLayer.data = dataString

        scalebarBG = mapscript.colorObj(255,255,255)
        outputMap.scalebar.status = mapscript.MS_EMBED
        outputMap.scalebar.outlinecolor = scalebarBG

        # Setup the default name for the output image
        # create a subdirectory in tmp in case it already isn't there (to keep it nice a tidy)
        os.popen("mkdir -p /tmp/terratruth_print_files").read()
        
        outputImageFile = '/tmp/terratruth_print_files/testmap%s.jpg'%time.time()
        # Save the image to temporary spot, in jpeg format (PNG was causing an error)
        outputMap.selectOutputFormat('JPEG')
        img = outputMap.draw()
        
        # save and reload because otherwise we don't have a real PIL image apparently.
        img.save(outputImageFile)
        img = Image.open(outputImageFile)
        
        if self.fields.get('confidential'):
            confImage = Image.open(os.path.join(settings.BASE_DIR,"media","images","confidential.gif"))
            img = watermark.watermark(img, confImage, (0, 0), 0.5)
        
        if self.fields.get('legendimages'):
            legend = self.createLegendImage()
            img = watermark.watermark(img, legend,(img.size[0]-legend.size[0],
                0), 1)
        
        img.save(outputImageFile)
        # Can use the outputImageFile to pass back to be inserted into PDF
        # Can return the outputImageUrl that contains the URL to image

        image = ImageReader(outputImageFile)
        return image
コード例 #28
0
    layer = layerObj(map)
    layer.name = coverageid
    layer.data = options.output
    layer.status = MS_ON
    layer.type = MS_LAYER_RASTER
    layer.setProjection("init=epsg:%d" % epsg)
    layer.setMetaData("wcs_srs", "epsg:%d" % epsg)
    layer.setMetaData("wcs_extent", extent)
    layer.setMetaData("wcs_size", "%d %d" % (width, height))
    layer.setMetaData("wcs_default_format", "application/gml+xml")

    # set band metadata
    layer.setMetaData("wcs_bandcount", str(len(bands)))
    layer.setMetaData("wcs_band_names",
                      " ".join([band['band_name'] for band in bands]))
    for band in bands:
        for key, value in iteritems(band):
            if value is None or key == "band_name":
                continue
            layer.setMetaData("%s_%s" % (band['band_name'], key), str(value))

    # append GML outputformat
    format = outputFormatObj("GDAL/GTiff", "GML")
    format.setExtension("xml")
    format.setMimetype("application/gml+xml")
    format.imagemode = MS_IMAGEMODE_FLOAT32
    map.appendOutputFormat(format)

    #save the map to the disk
    map.save(options.map)
コード例 #29
0
ファイル: ms_renderer.py プロジェクト: adorsk-noaa/georefine
 def get_outputFormatObj(self, format_id='image/gif'):
     format_def = output_formats[format_id]
     outputFormatObj = ms.outputFormatObj(format_def['driver'])
     for attr in ['mimetype', 'imagemode', 'extension', 'transparent']:
         setattr(outputFormatObj, attr, format_def[attr])
コード例 #30
0
 def testOutputFormatConstructor(self):
     new_format = mapscript.outputFormatObj('GDAL/GTiff', 'gtiff')
     # assert new_format.refcount == 1, new_format.refcount
     assert new_format.name == 'gtiff'
     assert new_format.mimetype == 'image/tiff'
コード例 #31
0
ファイル: main.py プロジェクト: djskl/pgmap
def get_output_fmt():
    output_fmt = outputFormatObj("GD/PNG", MAP_IMG_TYPE)
    output_fmt.mimetype = "image/png"
    output_fmt.extension = MAP_IMG_TYPE
    output_fmt.imagemode = MS_IMAGEMODE_RGBA
    output_fmt.transparent = MS_ON
コード例 #32
0
 def testOutputFormatConstructor(self):
     new_format = mapscript.outputFormatObj('GDAL/GTiff', 'gtiff')
     # assert new_format.refcount == 1, new_format.refcount
     assert new_format.name == 'gtiff'
     assert new_format.mimetype == 'image/tiff'