0
    def build_image(image_data):
        template = Image.open("path/to/file/template.jpg")
        draw = ImageDraw.Draw(template)
        draw.text("(553,431)", f"{image_data.text}", fill=4324234, font=font)
        file = InMemoryUploadedFile(template, None, 'result.jpg', 'image/jpeg', template.tell, None)
        return FileResponse(file, as_attachment=True, filename='result.jpg')

I need to return the image that was modified, without saving it to the database. The above code gives the following error:

A server error occurred.  Please contact the administrator.
  1. I also tried the following option:
rea_response = HttpResponse(template, content_type='image/png')
        rea_response['Content-Disposition'] = 'attachment; filename={}'.format('result.png')
        return rea_response

But in this case, I get a corrupted file. (This format is not supported).

django==3.0.6

1 Answers1

0

If you want to return raw bytes (of the image), then pass a file handler to Image.save() as said here.

E.g.

import io

def foo():
    template = Image.open("path/to/file/template.jpg")
    draw = ImageDraw.Draw(template)
    draw.text("(553,431)", f"{image_data.text}", fill=4324234, font=font)
    buff = io.BytesIO()
    template.save(buff, format='JPEG')
    return buff
s0mbre
  • 361
  • 2
  • 14
  • This all happens in the view. The user clicks on the button, and he starts downloading a file in jpg format, which was generated in pillow, by changing the template. If I do as in your answer, and pass buff to ```FileResponse(buff, as_attachment=True, filename='result.jpg')``` I have an endless load going on. – whiskeyhoney Jul 12 '21 at 04:09
  • Then why not saving the image to a temp static file and give this link for downloading? See [django docs on static files](https://docs.djangoproject.com/en/3.2/howto/static-files/) and [this topic on SO](https://stackoverflow.com/questions/22700097/how-to-point-correctly-to-static-image-in-django) – s0mbre Jul 12 '21 at 04:22