Last active
May 9, 2022 04:31
-
-
Save edigiacomo/2ab319e572ca26aedcd0 to your computer and use it in GitHub Desktop.
Django view that converts a RasterField to PNG
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponse | |
from django.db.models import BinaryField, Func, F, Value, CharField | |
from .models import MyModel | |
def view_png(request): | |
"""Return a PostGIS raster as a PNG image.""" | |
# MyModel is a django model with a RasterField named "rast". | |
# Note: ST_AsGdalRaster can reproject the data, | |
# see http://postgis.net/docs/manual-dev/RT_ST_AsGDALRaster.html | |
o = MyModel.objects.all().annotate( | |
img=Func( | |
F('rast'), | |
Value('PNG', output_field=CharField()), | |
output_field=BinaryField(), | |
function='st_asgdalraster' | |
) | |
).first() | |
response = HttpResponse(content_type="image/png") | |
response.write(o.image.tobytes()) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment