Пример #1
0
def preview(request, layer_slug):
    """Home page for layers.

    :param request: The web request.
    :param layer_slug: The layer
    """
    layer = get_object_or_404(Layer, slug=layer_slug)

    layer_path = os.path.join(
        settings.MEDIA_ROOT, 'layers', layer.slug, 'raw')
    map_layer = QgsVectorLayer(layer_path, layer.name, 'ogr')
    QgsMapLayerRegistry.instance().addMapLayer(map_layer)
    layer_uri = tempfile.NamedTemporaryFile(
        suffix='.png', prefix='inasafe-web-', dir='/tmp/').name
    # create image
    image = QImage(QSize(100, 100), QImage.Format_ARGB32_Premultiplied)

    # set image's background color
    color = QColor(255, 255, 255)
    image.fill(color.rgb())

    # create painter
    p = QPainter()
    p.begin(image)
    p.setRenderHint(QPainter.Antialiasing)

    renderer = QgsMapRenderer()

    # set layer set
    layers = [map_layer.id()]  # add ID of every layer
    renderer.setLayerSet(layers)

    # set extent
    rect = QgsRectangle(renderer.fullExtent())
    rect.scale(1.1)
    renderer.setExtent(rect)

    # set output size
    renderer.setOutputSize(image.size(), image.logicalDpiX())

    # do the rendering
    renderer.render(p)

    p.end()

    # clean up
    registry_list = qgis_layers()
    QgsMapLayerRegistry.instance().removeMapLayer(map_layer.id())
    print registry_list

    # save image
    image.save(layer_uri, 'png')
    with open(layer_uri, 'rb') as f:
        response = HttpResponse(f.read(), content_type='png')
    os.remove(layer_uri)

    return response
Пример #2
0
    def draw_window(self, x, y, progress, render_image):
        nr_jobs = len(progress)
        grid_size = int(math.ceil(math.sqrt(nr_jobs)))

        for index, job in enumerate(progress):
            y_off = index / grid_size
            x_off = index - (y_off * grid_size)
            color = QColor(*self.state_colors[job.status])
            render_image.setPixel(x + x_off, y + y_off, color.rgb())
Пример #3
0
    def draw_window(self, x, y, progress, render_image):
        nr_jobs = len(progress)
        grid_size = int(math.ceil(math.sqrt(nr_jobs)))

        for index, job in enumerate(progress):
            y_off = index / grid_size
            x_off = index - (y_off * grid_size)
            color = QColor(*self.state_colors[job.status])
            render_image.setPixel(x + x_off, y + y_off, color.rgb())
Пример #4
0
    def __init__(self, points, rgb, alpha):

        self.points = points
        colour = QColor(rgb)
        self.red = colour.red()
        self.green = colour.green()
        self.blue = colour.blue()
        colour.setAlphaF(alpha)
        self.alpha = alpha
        self.rgba = colour.rgb()
        self.projected = []
Пример #5
0
	def __init__( self, parent ):
		super( HueSliderWidget, self ).__init__( parent )
		self.setFixedSize( parent.width(), parent.height() )
		self.value = 0
		size = 100
		self.colorImage = QtGui.QImage( 1, size, QtGui.QImage.Format_RGB32 )
		c = QColor()
		for y in range( 0, size ):
			k = y/float(size)
			c.setHsvF( k, 1.0, 1.0 )
			self.colorImage.setPixel( 0, y, c.rgb() )
		self.setCursor( Qt.PointingHandCursor )
Пример #6
0
	def __init__( self, parent ):
		super( AlphaSliderWidget, self ).__init__( parent )
		self.setFixedSize( parent.width(), parent.height() )
		self.setCursor( Qt.PointingHandCursor )
		self.value = 0
		size = 100
		self.colorImage = QtGui.QImage( size, 1, QtGui.QImage.Format_RGB32 )
		c = QColor()
		for x in range( 0, size ):
			k = x/float(size)
			c.setHsvF( 1.0, 0.0, k )
			self.colorImage.setPixel( x, 0, c.rgb() )
Пример #7
0
def makeImage(dow, tod):
    layer = qgis.utils.iface.activeLayer()
    renderer = layer.rendererV2()

    renderer.setClassAttribute("-predicted_pickup_" + str(dow) + "_" +
                               str(tod))

    #http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/composer.html

    # create image
    img = QImage(QSize(800, 1000), QImage.Format_ARGB32_Premultiplied)

    # set image's background color
    color = QColor(255, 255, 255)
    img.fill(color.rgb())

    # create painter
    p = QPainter()
    p.begin(img)
    p.setRenderHint(QPainter.Antialiasing)

    render = QgsMapRenderer()

    # set layer set
    layers_to_draw = []

    for l in iface.mapCanvas().layers():
        if l.name() in ['grid', 'nyc_projected']:
            layers_to_draw.append(l.id())

    #lst = [layer.id()]
    lst = layers_to_draw  # add ID of every layer
    render.setLayerSet(lst)

    # set extent
    rect = QgsRectangle(render.fullExtent())
    rect.scale(1.1)
    render.setExtent(rect)

    # set output size
    render.setOutputSize(img.size(), img.logicalDpiX())

    # do the rendering
    render.render(p)
    p.end()

    # create file path
    imPath = '/Users/danil/Documents/GitHub/dmc/notebooks/workshop-1/-screenshots/'
    imName = str(dow) + "_" + str(tod)

    # save image
    img.save(imPath + imName + '.png', "png")
Пример #8
0
def generateHSVImage( w, h, hue, img = None ):
	if not img:
		img = QtGui.QImage( w, h, QtGui.QImage.Format_RGB32 )
	du = 1.0/w
	dv = 1.0/h
	c = QColor()
	for y in range( 0, h ):
		for x in range( 0, w ):
			s = du * x
			v = 1.0 - dv * y
			c.setHsvF( hue, s, v )
			img.setPixel( x, y, c.rgb() )
	return img
def run_script(iface):
    canvas = iface.mapCanvas()

    img = QImage(QSize(1920, 1080), QImage.Format_ARGB32_Premultiplied)
    color = QColor(255, 255, 255)
    p = QPainter(img)

    for path in paths:
        #accessibilityLayer.setDataProvider(path)

        # http://www.qgisworkshop.org/html/workshop/python_in_qgis_tutorial2.html
        rlayer = iface.addRasterLayer(path)
        # http://gis.stackexchange.com/questions/26846
        rlayer.loadNamedStyle(
            '/home/matthewc/microaccessibility/times/colors.qml')

        # add the vector layers
        poly = iface.addVectorLayer(
            'dbname=\'matthewc\' host=localhost port=5432 user=\'matthewc\' password=\'password\' sslmode=disable key=\'tid\' srid=4326 type=POLYGON table="public"."ucsb_final_polygon" (way) sql=',
            'poly', 'postgres')
        poly.loadNamedStyle('/home/matthewc/microaccessibility/times/poly.qml')

        line = iface.addVectorLayer(
            'dbname=\'matthewc\' host=localhost port=5432 user=\'matthewc\' password=\'password\' sslmode=disable key=\'tid\' srid=4326 type=LINESTRING table="public"."ucsb_final_line" (way) sql=',
            'line', 'postgres')
        line.loadNamedStyle('/home/matthewc/microaccessibility/times/line.qml')

        renderer = canvas.mapRenderer()

        img.fill(color.rgb())
        p.begin(img)
        p.setRenderHint(QPainter.Antialiasing)
        renderer.setOutputSize(img.size(), img.logicalDpiX())
        renderer.render(p)

        p.setFont(QFont("Ubuntu", 48, QFont.Bold))
        p.setPen(QColor(0, 0, 0))
        p.drawText(10, 58, parseToTime(path))

        p.end()
        img.save(path + ".png", "png")

        QgsMapLayerRegistry.instance().removeMapLayer(rlayer.id())
        QgsMapLayerRegistry.instance().removeMapLayer(poly.id())
        QgsMapLayerRegistry.instance().removeMapLayer(line.id())
Пример #10
0
def run_script(iface):
    canvas = iface.mapCanvas()

    img = QImage(QSize(1920, 1080), QImage.Format_ARGB32_Premultiplied)
    color = QColor(255, 255, 255)
    p = QPainter(img)

    for path in paths:
        #accessibilityLayer.setDataProvider(path)

        # http://www.qgisworkshop.org/html/workshop/python_in_qgis_tutorial2.html
        rlayer = iface.addRasterLayer(path)
        # http://gis.stackexchange.com/questions/26846
        rlayer.loadNamedStyle('/home/matthewc/microaccessibility/times/colors.qml')

        # add the vector layers
        poly = iface.addVectorLayer('dbname=\'matthewc\' host=localhost port=5432 user=\'matthewc\' password=\'password\' sslmode=disable key=\'tid\' srid=4326 type=POLYGON table="public"."ucsb_final_polygon" (way) sql=', 'poly', 'postgres')
        poly.loadNamedStyle('/home/matthewc/microaccessibility/times/poly.qml')
        
        line = iface.addVectorLayer('dbname=\'matthewc\' host=localhost port=5432 user=\'matthewc\' password=\'password\' sslmode=disable key=\'tid\' srid=4326 type=LINESTRING table="public"."ucsb_final_line" (way) sql=', 'line', 'postgres')
        line.loadNamedStyle('/home/matthewc/microaccessibility/times/line.qml')

        renderer = canvas.mapRenderer()

        img.fill(color.rgb())
        p.begin(img)
        p.setRenderHint(QPainter.Antialiasing)
        renderer.setOutputSize(img.size(), img.logicalDpiX())
        renderer.render(p)
        
        p.setFont(QFont("Ubuntu", 48, QFont.Bold))
        p.setPen(QColor(0,0,0))
        p.drawText(10, 58, parseToTime(path))

        p.end()
        img.save(path + ".png", "png")

        QgsMapLayerRegistry.instance().removeMapLayer(rlayer.id())
        QgsMapLayerRegistry.instance().removeMapLayer(poly.id())
        QgsMapLayerRegistry.instance().removeMapLayer(line.id())
Пример #11
0
def renderLayers(size, layers, imageFileName):

    imgSize = QSize(size, size)

    # create image
    img = QImage(imgSize, QImage.Format_RGB32)

    # set image's background color
    color = QColor(255, 255, 255)
    img.fill(color.rgb())

    # create painter
    p = QPainter()
    p.begin(img)
    p.setRenderHint(QPainter.Antialiasing)

    render = QgsMapRenderer()

    # set layer set
    render.setLayerSet(layers.keys())

    # set extent
    rect = QgsRectangle(render.fullExtent())
    render.setExtent(rect)

    # set output size
    render.setOutputSize(img.size(), img.logicalDpiX())

    print "render()"
    # do the rendering
    render.render(p)
    p.end()
    print "    ...Done"

    print "save(" + imageFileName + ")"
    # save image
    img.save(imageFileName)
    print "    ...Done"
Пример #12
0
def main():
    # supply path to qgis install location
    QgsApplication.setPrefixPath("/usr/share/qgis", True)

    # create a reference to the QgsApplication, setting the
    # second argument to False disables the GUI
    qgs = QgsApplication([], False)

    # load providers
    qgs.initQgis()

    fileName = sys.argv[1]
    layerStyle = sys.argv[2]
    destinationFile = sys.argv[3]

    fileInfo = QFileInfo(fileName)
    baseName = fileInfo.baseName()
    rlayer = QgsRasterLayer(fileName, baseName)
    if not rlayer.isValid():
        print "Layer failed to load!"

    rlayer.loadNamedStyle(layerStyle)

    QgsMapLayerRegistry.instance().addMapLayer(rlayer)

    # create image
    minsize = 2048
    factor = 1
    w = rlayer.width()
    h = rlayer.height()

    if w < minsize or h < minsize:
        if h > w:
            factor = minsize / h
        else:
            factor = minsize / w

    img = QImage(QSize(w * factor, h * factor),
                 QImage.Format_ARGB32_Premultiplied)

    # set image's background color (can get noise otherwise)
    color = QColor(255, 255, 255)
    img.fill(color.rgb())

    # create painter
    p = QPainter()
    p.begin(img)
    p.setRenderHint(QPainter.Antialiasing)

    render = QgsMapRenderer()

    # set layer set
    lst = [rlayer.id()]  # add ID of every layer
    render.setLayerSet(lst)

    # set extent
    rect = QgsRectangle(render.fullExtent())
    rect.scale(1.0)

    render.setExtent(rect)

    # set output size
    render.setOutputSize(img.size(), img.logicalDpiX())

    # do the rendering
    render.render(p)
    p.end()

    # save image
    img.save(destinationFile, "png")

    QgsApplication.exitQgis()
Пример #13
0
def main():
    # supply path to qgis install location
    QgsApplication.setPrefixPath("/usr/share/qgis", True)

    # create a reference to the QgsApplication, setting the
    # second argument to False disables the GUI
    qgs = QgsApplication([], False)
    
    # load providers
    qgs.initQgis()

    fileName = sys.argv[1]
    layerStyle = sys.argv[2]
    destinationFile = sys.argv[3]


    fileInfo = QFileInfo(fileName)
    baseName = fileInfo.baseName()
    rlayer = QgsRasterLayer(fileName, baseName)
    if not rlayer.isValid():
        print "Layer failed to load!"

    rlayer.loadNamedStyle(layerStyle)

    QgsMapLayerRegistry.instance().addMapLayer(rlayer)

    # create image
    minsize = 2048
    factor = 1
    w = rlayer.width()
    h = rlayer.height()

    if w < minsize or h < minsize:
        if h > w:
            factor = minsize / h
        else:
            factor = minsize / w

    img = QImage(QSize(w * factor, h * factor), QImage.Format_ARGB32_Premultiplied)

    # set image's background color (can get noise otherwise)
    color = QColor(255, 255, 255)
    img.fill(color.rgb())

    # create painter
    p = QPainter()
    p.begin(img)
    p.setRenderHint(QPainter.Antialiasing)
    
    render = QgsMapRenderer()
    
    # set layer set
    lst = [rlayer.id()]  # add ID of every layer
    render.setLayerSet(lst)
    
    # set extent
    rect = QgsRectangle(render.fullExtent())
    rect.scale(1.0)
    
    render.setExtent(rect)
    
    # set output size
    render.setOutputSize(img.size(), img.logicalDpiX())
    
    # do the rendering
    render.render(p)
    p.end()
    
    # save image
    img.save(destinationFile,"png")

    QgsApplication.exitQgis()
Пример #14
0
    def updateDisplay(self):
        ''' Add map(s) of all QF components to the canvas based on what's selected in self.lstTimes'''
        timestamps = [
            pd.datetime.strptime(newItem.text(), '%Y-%m-%d %H:%M')
            for newItem in self.lstTimes.selectedItems()
        ]

        for t in timestamps:
            outs = pd.read_csv(self.model.getFileList()[t],
                               header=0,
                               index_col=0)
            outLayer = self.outputLayer
            # Make sure the output file is properly appended (this gets evaluated for non-extra-disaggregated datasets)
            # because I didn't set an output shapefile path properly

            if os.path.split(self.outputLayer)[0] == '':
                outLayer = os.path.join(self.model.downscaledPath,
                                        os.path.split(self.outputLayer)[1])

            fileToPopulate = self.outputLayer
            new_layer = populateShapefileFromTemplate(
                outs,
                self.featureIdField,
                outLayer,
                int(self.outputEPSG),
                title=t.strftime(' %Y-%m-%d %H:%M UTC'))

            # Set ranges suited to all the different QF types
            range_minima = [0, 0.000001, 0.1, 1, 10, 100]
            range_maxima = [0.000001, 0.1, 1, 10, 100, 1000]
            colours = [
                '#CECECE', '#FEE6CE', '#FDAE6B', '#F16913', '#D94801',
                '#7F2704'
            ]
            opacity = 1
            for component in self.componentTranslation.values():
                layerName = component + t.strftime(' %Y-%m-%d %H:%M UTC')
                if component == self.componentTranslation.values()[0]:
                    colourRanges(new_layer, component, opacity, range_minima,
                                 range_maxima, colours)
                    new_layer.setLayerName(layerName)
                    layerId = new_layer.id()
                    QgsMapLayerRegistry.instance().addMapLayer(new_layer)
                    proportion = new_layer.extent().height(
                    ) / new_layer.extent().width()

                else:
                    # Have to clone. Can't seem to duplicate a map layer...
                    layer = duplicateVectorLayer(new_layer)
                    layer.setLayerName(layerName)
                    colourRanges(layer, component, opacity, range_minima,
                                 range_maxima, colours)
                    layerId = layer.id()
                    QgsMapLayerRegistry.instance().addMapLayer(layer)
                    proportion = layer.extent().height() / layer.extent(
                    ).width()

                maxSize = 2000  # Max size of output image
                if proportion > 1:
                    hSize = maxSize / proportion
                    vSize = maxSize
                else:
                    hSize = maxSize
                    vSize = maxSize * proportion

                # create image in proportion with layer
                img = QImage(QSize(hSize, vSize),
                             QImage.Format_ARGB32_Premultiplied)

                # set image's background color
                color = QColor(255, 255, 255)
                img.fill(color.rgb())

                # create painter
                p = QPainter()
                p.begin(img)
                p.setRenderHint(QPainter.Antialiasing)

                render = QgsMapRenderer()

                # set layer set
                lst = [layerId]  # add ID of every layer
                render.setLayerSet(lst)

                # set extent
                rect = QgsRectangle(render.fullExtent())
                rect.scale(1.1)
                render.setExtent(rect)

                # set output size
                render.setOutputSize(img.size(), img.logicalDpiX())

                # do the rendering
                render.render(p)
                p.end()

                # save image
                img.save(
                    os.path.join(
                        self.model.renderPath,
                        component + t.strftime('_%Y-%m-%d_%H-%M_UTC.png')),
                    "png")