Ejemplo n.º 1
0
    def _initRenderer(self):
        # set up a renderer
        labeling = QgsPalLabeling()
        renderer = QgsMapRenderer()
        renderer.setDestinationCrs(self.exportSettings.crs)
        renderer.setProjectionsEnabled(True)
        renderer.setLabelingEngine(labeling)

        # save renderer
        self._labeling = labeling
        self._renderer = renderer
Ejemplo n.º 2
0
  def _initRenderer(self):
    # set up a renderer
    labeling = QgsPalLabeling()
    renderer = QgsMapRenderer()
    renderer.setDestinationCrs(self.context.crs)
    renderer.setProjectionsEnabled(True)
    renderer.setLabelingEngine(labeling)

    # save renderer
    self._labeling = labeling
    self._renderer = renderer
Ejemplo n.º 3
0
 def createimage(self, extent, crs, outputsize):
     render = QgsMapRenderer()
     render.setLayerSet(self.loadedlayers.values())
     render.setProjectionsEnabled(True)
     render.setDestinationCrs(crs)
     render.setExtent(extent)
     
     img = QImage(outputsize, QImage.Format_ARGB32_Premultiplied)
     img.fill(Qt.transparent) #needed, apparently the QImage() is not empty
                 
     painter = QPainter()
     painter.begin(img)
     painter.setRenderHint(QPainter.Antialiasing)
     render.setOutputSize(img.size(), img.logicalDpiX())
     log("about to render")
     render.render(painter)
     log("just rendered")
     painter.end()
     return img
Ejemplo n.º 4
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        vectorFileInfo = QFileInfo( self.TEST_DATA_DIR + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )

        QgsMapLayerRegistry.instance().addMapLayers( [mVectorLayer] )

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append( mVectorLayer.id() )
        mMapRenderer.setLayerSet( layerStringList )
        mMapRenderer.setProjectionsEnabled( True )
        mMapRenderer.setMapUnits( QGis.Meters )

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid( 2154 )
        mMapRenderer.setDestinationCrs( crs )

        self.mComposition = QgsComposition( mMapRenderer )
        self.mComposition.setPaperSize( 297, 210 )

        # fix the renderer, fill with green
        props = { "color": "0,127,0" }
        fillSymbol = QgsFillSymbolV2.createSimple( props )
        renderer = QgsSingleSymbolRendererV2( fillSymbol )
        mVectorLayer.setRendererV2( renderer )

        # the atlas map
        self.mAtlasMap = QgsComposerMap( self.mComposition, 20, 20, 130, 130 )
        self.mAtlasMap.setFrameEnabled( True )
        self.mComposition.addComposerMap( self.mAtlasMap )

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer( mVectorLayer )
        self.mAtlas.setEnabled( True )
        self.mComposition.setAtlasMode( QgsComposition.ExportAtlas )

        # an overview
        mOverview = QgsComposerMap( self.mComposition, 180, 20, 50, 50 )
        mOverview.setFrameEnabled( True )
        mOverview.setOverviewFrameMap( self.mAtlasMap.id() )
        self.mComposition.addComposerMap( mOverview )
        nextent = QgsRectangle( 49670.718, 6415139.086, 699672.519, 7065140.887 )
        mOverview.setNewExtent( nextent )

        # set the fill symbol of the overview map
        props2 = { "color": "127,0,0,127" }
        fillSymbol2 = QgsFillSymbolV2.createSimple( props2 )
        mOverview.setOverviewFrameMapSymbol( fillSymbol2 )

        # header label
        self.mLabel1 = QgsComposerLabel( self.mComposition )
        self.mComposition.addComposerLabel( self.mLabel1 )
        self.mLabel1.setText( "[% \"NAME_1\" %] area" )
        self.mLabel1.setFont( QgsFontUtils.getStandardTestFont() )
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect( QRectF( 150, 5, 60, 15 ) )

        qWarning( "header label font: %s exactMatch:%s" % ( self.mLabel1.font().toString(), self.mLabel1.font().exactMatch() ) )

        # feature number label
        self.mLabel2 = QgsComposerLabel( self.mComposition )
        self.mComposition.addComposerLabel( self.mLabel2 )
        self.mLabel2.setText( "# [%$feature || ' / ' || $numfeatures%]" )
        self.mLabel2.setFont( QgsFontUtils.getStandardTestFont() )
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect( QRectF( 150, 200, 60, 15 ) )

        qWarning( "feature number label font: %s exactMatch:%s" % ( self.mLabel2.font().toString(), self.mLabel2.font().exactMatch() ) )

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
Ejemplo n.º 5
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(
                os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(),
                                      vectorFileInfo.completeBaseName(), "ogr")

        QgsMapLayerRegistry.instance().addMapLayers([mVectorLayer])

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append(mVectorLayer.id())
        mMapRenderer.setLayerSet(layerStringList)
        mMapRenderer.setProjectionsEnabled(True)
        mMapRenderer.setMapUnits(QGis.Meters)

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        mMapRenderer.setDestinationCrs(crs)

        self.mComposition = QgsComposition(mMapRenderer)
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbolV2.createSimple(props)
        renderer = QgsSingleSymbolRendererV2(fillSymbol)
        mVectorLayer.setRendererV2(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        mOverview.setFrameEnabled(True)
        mOverview.setOverviewFrameMap(self.mAtlasMap.id())
        self.mComposition.addComposerMap(mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbolV2.createSimple(props2)
        mOverview.setOverviewFrameMapSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" %
            (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText("# [%$feature || ' / ' || $numfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning(
            "feature number label font: %s exactMatch:%s" %
            (self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()

        shutil.rmtree(tmppath, True)
Ejemplo n.º 6
0
    def identify(self, params):
        self.check_required_params(params)

        feature_collections = []

        with change_directory(self.project_root):

            crs = QgsCoordinateReferenceSystem()
            crs.createFromSrid(params.get('srs'))

            search_box = self._calcSearchBox(
                params.get('bbox'), params.get('image_size')[0],
                params.get('image_size')[1],
                params.get('click_point')[0], params.get('click_point')[1]
            )

            # initialize mapRenderer and a rendering context in order to be
            # to check if a feature will actually be rendered
            # we don't want to return features that are not visible
            img = QImage(QSize(
                settings.SUNLUMO_GFI_BUFFER*2, settings.SUNLUMO_GFI_BUFFER*2),
                QImage.Format_ARGB32_Premultiplied
            )
            dpm = 1 / 0.00028
            img.setDotsPerMeterX(dpm)
            img.setDotsPerMeterY(dpm)

            mapRenderer = QgsMapRenderer()
            mapRenderer.clearLayerCoordinateTransforms()
            mapRenderer.setOutputSize(QSize(
                settings.SUNLUMO_GFI_BUFFER*2, settings.SUNLUMO_GFI_BUFFER*2),
                img.logicalDpiX()
            )

            mapRenderer.setDestinationCrs(crs)
            mapRenderer.setProjectionsEnabled(True)
            mapUnits = crs.mapUnits()
            mapRenderer.setMapUnits(mapUnits)

            mapExtent = QgsRectangle(*search_box)
            mapRenderer.setExtent(mapExtent)

            renderContext = QgsRenderContext()
            renderContext.setExtent(mapRenderer.extent())
            renderContext.setRasterScaleFactor(1.0)
            renderContext.setMapToPixel(mapRenderer.coordinateTransform())
            renderContext.setRendererScale(mapRenderer.scale())
            renderContext.setScaleFactor(mapRenderer.outputDpi() / 25.4)
            renderContext.setPainter(None)

            qfr = QgsFeatureRequest()
            search_rectangle = QgsRectangle(*search_box)
            qfr.setFilterRect(search_rectangle)

            for q_layer in params.get('query_layers'):
                layer = self.layerRegistry.mapLayer(q_layer)

                if layer.type() == QgsMapLayer.RasterLayer:
                    # skip raster layer processing
                    continue

                # update layer fields (expressions, calculated, joined)
                layer.updateFields()

                scaleCalc = QgsScaleCalculator(
                    (img.logicalDpiX() + img.logicalDpiY()) / 2,
                    mapRenderer.destinationCrs().mapUnits()
                )
                scaleDenom = scaleCalc.calculate(mapExtent, img.width())

                # skip the layer if it's not visible at the current map scale
                if layer.hasScaleBasedVisibility():
                    if not(layer.minimumScale()
                            < scaleDenom < layer.maximumScale()):
                        continue

                # check if features actually intersect search rectangle
                intersected_features = self._intersectedFeatures(
                    layer.getFeatures(qfr), search_rectangle
                )
                # visible features generator
                visible_features = self._visibleFeatures(
                    layer, renderContext, intersected_features
                )
                layer_features = [featureToGeoJSON(
                    feature.id(), feature.geometry(),
                    self._collectAttributes(layer, feature)
                ) for feature in visible_features
                ]

                feature_collections.append(layer_features)

            return writeGeoJSON(chain(*feature_collections))
Ejemplo n.º 7
0
    def saveControlImage(self, tmpimg=''):
        # don't save control images for RenderVsOtherOutput (Vs) tests, since
        # those control images belong to a different test result
        if ('PAL_CONTROL_IMAGE' not in os.environ or 'Vs' in self._TestGroup):
            return
        imgpath = self.controlImagePath()
        # print "saveControlImage: {0}".format(imgpath)
        testdir = os.path.dirname(imgpath)
        if not os.path.exists(testdir):
            os.makedirs(testdir)
        imgbasepath = \
            os.path.join(testdir,
                         os.path.splitext(os.path.basename(imgpath))[0])
        for f in glob.glob(imgbasepath + '.*'):
            if os.path.exists(f):
                os.remove(f)
        if tmpimg and os.path.exists(tmpimg):
            shutil.copyfile(tmpimg, imgpath)
        else:
            print '\nsaveControlImage.render(): entered'
            print '{0}.{1}'.format(self._TestGroup, self._TestFunction)

            ms = self._MapSettings  # class settings
            """:type: QgsMapSettings"""
            if self._TestMapSettings is not None:
                ms = self._TestMapSettings  # per test settings
            print 'self._MapSettings...'
            print 'ms.layers(): {0}'.format(
                [self._MapRegistry.mapLayer(i).name() for i in ms.layers()])
            print 'ms.outputSize(): {0} x {1}'.format(ms.outputSize().width(),
                                                      ms.outputSize().height())
            print 'ms.outputDpi(): {0}'.format(ms.outputDpi())
            print 'ms.mapUnits(): {0}'.format(ms.mapUnits())
            print 'ms.extent(): {0}'.format(ms.extent().toString())
            print 'ms.hasCrsTransformEnabled(): {0}'.format(
                ms.hasCrsTransformEnabled())
            print 'ms.destinationCrs(): {0}'.format(
                ms.destinationCrs().authid())

            # pal = QgsPalLabeling()
            pal = self._Pal.clone()  # or custom settings are lost
            pal.init(ms)
            r = QgsMapRenderer()
            r.setLabelingEngine(pal)

            # this seems too redundant
            r.setOutputSize(ms.outputSize(), ms.outputDpi())
            r.setMapUnits(ms.mapUnits())
            r.setExtent(ms.extent())
            r.setProjectionsEnabled(ms.hasCrsTransformEnabled())
            r.setDestinationCrs(ms.destinationCrs())
            r.setLayerSet(ms.layers())

            ctx = r.rendererContext()
            ctx.setDrawEditingInformation(
                ms.testFlag(QgsMapSettings.DrawEditingInfo))
            ctx.setForceVectorOutput(
                ms.testFlag(QgsMapSettings.ForceVectorOutput))
            ctx.setUseAdvancedEffects(
                ms.testFlag(QgsMapSettings.UseAdvancedEffects))

            image = QImage(ms.outputSize(), QImage.Format_ARGB32)
            image.fill(ms.backgroundColor().rgb())
            image.setDotsPerMeterX(ms.outputDpi() / 25.4 * 1000)
            image.setDotsPerMeterY(ms.outputDpi() / 25.4 * 1000)

            p = QPainter(image)
            r.render(p)
            p.end()

            if not image.save(imgpath, 'png'):
                os.unlink(imgpath)

            # delete extraneous world file (always generated)
            # wrld_file = imgbasepath + '.PNGw'
            # if os.path.exists(wrld_file):
            #     os.remove(wrld_file)

        if not os.path.exists(imgpath):
            raise OSError('Control image not created: {0}'.format(imgpath))
Ejemplo n.º 8
0
    def saveControlImage(self, tmpimg=''):
        # don't save control images for RenderVsOtherOutput (Vs) tests, since
        # those control images belong to a different test result
        if ('PAL_CONTROL_IMAGE' not in os.environ
                or 'Vs' in self._TestGroup):
            return
        imgpath = self.controlImagePath()
        # print "saveControlImage: {0}".format(imgpath)
        testdir = os.path.dirname(imgpath)
        if not os.path.exists(testdir):
            os.makedirs(testdir)
        imgbasepath = \
            os.path.join(testdir,
                         os.path.splitext(os.path.basename(imgpath))[0])
        for f in glob.glob(imgbasepath + '.*'):
            if os.path.exists(f):
                os.remove(f)
        if tmpimg and os.path.exists(tmpimg):
            shutil.copyfile(tmpimg, imgpath)
        else:
            print '\nsaveControlImage.render(): entered'
            print '{0}.{1}'.format(self._TestGroup, self._TestFunction)

            ms = self._MapSettings  # class settings
            """:type: QgsMapSettings"""
            if self._TestMapSettings is not None:
                ms = self._TestMapSettings  # per test settings
            print 'self._MapSettings...'
            print 'ms.layers(): {0}'.format(
                [self._MapRegistry.mapLayer(i).name() for i in ms.layers()]
            )
            print 'ms.outputSize(): {0} x {1}'.format(
                ms.outputSize().width(), ms.outputSize().height())
            print 'ms.outputDpi(): {0}'.format(ms.outputDpi())
            print 'ms.mapUnits(): {0}'.format(ms.mapUnits())
            print 'ms.extent(): {0}'.format(ms.extent().toString())
            print 'ms.hasCrsTransformEnabled(): {0}'.format(
                ms.hasCrsTransformEnabled())
            print 'ms.destinationCrs(): {0}'.format(
                ms.destinationCrs().authid())

            # pal = QgsPalLabeling()
            pal = self._Pal.clone()  # or custom settings are lost
            pal.init(ms)
            r = QgsMapRenderer()
            r.setLabelingEngine(pal)

            # this seems too redundant
            r.setOutputSize(ms.outputSize(), ms.outputDpi())
            r.setMapUnits(ms.mapUnits())
            r.setExtent(ms.extent())
            r.setProjectionsEnabled(ms.hasCrsTransformEnabled())
            r.setDestinationCrs(ms.destinationCrs())
            r.setLayerSet(ms.layers())

            ctx = r.rendererContext()
            ctx.setDrawEditingInformation(
                ms.testFlag(QgsMapSettings.DrawEditingInfo))
            ctx.setForceVectorOutput(
                ms.testFlag(QgsMapSettings.ForceVectorOutput))
            ctx.setUseAdvancedEffects(
                ms.testFlag(QgsMapSettings.UseAdvancedEffects))

            image = QImage(ms.outputSize(), QImage.Format_ARGB32)
            image.fill(ms.backgroundColor().rgb())
            image.setDotsPerMeterX(ms.outputDpi() / 25.4 * 1000)
            image.setDotsPerMeterY(ms.outputDpi() / 25.4 * 1000)

            p = QPainter(image)
            r.render(p)
            p.end()

            if not image.save(imgpath, 'png'):
                os.unlink(imgpath)

            # delete extraneous world file (always generated)
            # wrld_file = imgbasepath + '.PNGw'
            # if os.path.exists(wrld_file):
            #     os.remove(wrld_file)

        if not os.path.exists(imgpath):
            raise OSError('Control image not created: {0}'.format(imgpath))
Ejemplo n.º 9
0
print("Image size: %dx%d" % (iwidth, iheight))

dpi = args.dpi

img = QImage(iwidth, iheight, QImage.Format_RGB32)
img.setDotsPerMeterX(dpi / 25.4 * 1000)
img.setDotsPerMeterY(dpi / 25.4 * 1000)
img.fill(qRgb(255, 255, 255))

dpi = img.logicalDpiX()
print("Image DPI: %d" % dpi)

render.setOutputSize(QSize(img.width(), img.height()), dpi)

render.setDestinationCrs(crs)
render.setProjectionsEnabled(True)
render.setMapUnits(crs.mapUnits())

render.setExtent(extent)
print("Scale: %f" % render.scale())

painter = QPainter(img)
painter.setRenderHint(QPainter.Antialiasing)
render.render(painter)
painter.end()

ba = QByteArray()
bf = QBuffer(ba)
bf.open(QIODevice.WriteOnly)
img.save(bf, 'PNG')