Django REST API to expose images

You are trying to return the raw image data and have Django REST Framework render the response. As the response should not be different based on the chosen format, you should be using a raw HttpResponse object.

return HttpResponse(resized_img, content_type="image/png")

Note that the content_type should reflect the content type of the returned response, which should match the content type of the image that is being resized.


The error that you are getting is because the Renderer classes are expecting text-based responses, not image data. Django REST Framework will not apply the custom renderers to HttpResponse classes, only to Django REST Framework Response classes.


I know it's a quite old question, but I found solution to this problem. You can use a custom renderer from Django Rest Framework to return image by Response. For example:

class CustomRenderer(renderers.BaseRenderer):
    media_type = 'image/png'
    format = 'png'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data

And in views you have to call this renderer by:

  • Decorator: @renderer_classes((CustomRenderer,))

or

  • Renderer classes: renderer_classes = (CustomRenderer, )

Note. Remember about the semicolon

If you are using decorator like @action you might have problem with call your renderer by decorator. In this case you have to use renderer_classes in @action decorator:

@action(methods=['get'], detail=True, renderer_classes=(CustomRenderer,))