3

I have a Raster file in which some cells have the value 0 and I would like to use pyqgis make them 100% transparent. I guess I have to use the QgsRasterTransparency class but I have no idea how.

I have a QgsRasterLayer object called rlayer and I can make a QgsRasterTransparency obejct, but I don't know how to apply the transparency on the rlayer object and how to define that the transparency only applies to those cells with value 0.

1 Answer 1

4

You can use following code for a single value as in your case.

rlayer = iface.activeLayer()

transparency  = rlayer.renderer().rasterTransparency()

pixel = QgsRasterTransparency.TransparentSingleValuePixel()

#setting value
pixel.min = 0
#setting transparency level
pixel.percentTransparent = 100

transparency.setTransparentSingleValuePixelList( [pixel] )

layer.triggerRepaint() 

However, for an interval of values it is preferable to use following code instead.

rlayer = iface.activeLayer()

transparency  = rlayer.renderer().rasterTransparency()

n = 2

pixels = [ QgsRasterTransparency.TransparentSingleValuePixel()
           for i in range(n) ]

min = [ min1, min2 ] # change min1, min2 for a numeric value
max = [ max1, max2 ] # change max1, max2 for a numeric value

trpcy = 100

for i, item in enumerate(pixels):
    item.min = min[i]
    item.max = max[i]
    item.percentTransparent = trpcy

transparency.setTransparentSingleValuePixelList( pixels )

layer.triggerRepaint() 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.