0

I want to generate a dynamically created png image with Pycairo and serve it usign Django. I read this: Serve a dynamically generated image with Django.

Is there a way to transport data from Pycairo surface directly into HTTP response? I'm doing this for now:

data = surface.to_rgba()
im = Image.frombuffer ("RGBA", (width, height), data, "raw", "RGBA", 0,1)
response = HttpResponse(mimetype="image/png")
im.save(response, "PNG")
return response

But it actually doesn't work because there isn't a to_rgba call (this call I found using Google code but doesn't work).

EDIT: The to_rgba can be replaced by the correct call get_data(), but I still want to know if I can bypass PIL altogether.

Community
  • 1
  • 1
huggie
  • 17,587
  • 27
  • 82
  • 139

2 Answers2

7
def someView(request):
  surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)
  context = cairo.Context(surface)
  # Draw something ...

  response = HttpResponse(mimetype="image/png")
  surface.write_to_png(response)
  return response
plexer
  • 4,542
  • 2
  • 23
  • 27
  • Thanks, I've yet to test it out because I'm actually asking this question for a friend. But this looks exactly like what I was asking for. Thank you. – huggie Jun 17 '10 at 06:28
  • In django 1.7 the `mimetype` argument was renamed `content_type` – Rick Mohr Mar 09 '15 at 15:35
0

You can try this: http://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django It's about SVG but I think it will be easy to adapt

miga
  • 126
  • 5