Skip to content

Instantly share code, notes, and snippets.

@edigiacomo
Last active May 9, 2022 04:31
Show Gist options
  • Save edigiacomo/2ab319e572ca26aedcd0 to your computer and use it in GitHub Desktop.
Save edigiacomo/2ab319e572ca26aedcd0 to your computer and use it in GitHub Desktop.
Django view that converts a RasterField to PNG
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