First, My Situation description is below:
I am developing a Django app demo. The demo can receive an image file from the user. Then my Django app will processing this image, like add some text or change the image size.
I am a newbie in Django, file stream and response. I try to do some search and research. But I can not find a suitable case. Maybe I did not describe my question by the accurate and appropriate keywords.
I don't want to save the processed image to the local disk first, and then get the file's local path back to Django web. I want to return the image directly to the browser in memory.
Incidentally, django does not seem to recommend reading the media files directly on the local disk. Both css and js need to be configured with static_path to work properly. In addition, according to my investigation, it seems that handling and returning files directly in memory is a more mainstream practice. Of course, I have just come into contact with this field. It may not be the case. I just want to introduce ideas to help describe this tricky problem.
My mistake is this: Now my django app can get the user's image and process it smoothly. I also find a cool way to convert the 'PIL Image object' to a 'BytesIO object'. Thanks to Stackoverflow. I found the way about BytesIO on Stackoverflow.
And the next step is, I want to return this processed image. NOW, The last status of the image is a 'BytesIO object'.
The code like these:
# Python CODE
# above is processing with PIL
# the image is the Image object
image = Image.composite(image, bg, image)
# below is my new code
# I wrote the on the head: import Bytes IO
byte_file = BytesIO()
image.save(byte_file, format='PNG')
image_data = byte_file.getvalue()
return image_data
And the html demo is:
<!-- HTML CODE -->
<div>
<img src='{{ image_data }}' />
</div>
And I see the result in Browser is:
<!-- Chrome developer tools watch the source code -->
<img src="b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\ ... ... />
I know there is only one small step left and I will be able to display the image. However, I just can't find the right way. Last night, I was depressed.I guess that a few lines of code can handle it. However, I was trapped in this because I was not familiar with the file flow.
I try the SECOND way:
# Python CODe
image_data = byte_file.getvalue()
return HttpResponse(image_data,content_type="image/png")
The html source is:
<img src="<HttpResponse status_code=200, "image/png">">
SECOND way: html source in Chrome dev tools
I felt Excited! But I can not display the image. I am sad.
How can I convert BytesIO type image data to url and display it in html page? Expected effect