Home>

I was thinking about creating an image of appropriate input information with PIL, expanding the file into a temporary directory, and displaying it in the browser.
I created a temporary directory with NamedTemporaryFile, created a file there, and specified it with an HTML img tag.
Is there any way to save the image created on the server side in memory and display it in the browser even if it is not a temporary directory?
python is supposed to use django with 3.7, and it is specified as MEDIA_URL =/media /.

font_color = (0, 0, 0)
im = Image.new ('RGBA', (60,60), (0, 0, 0, 0))
draw = ImageDraw.Draw (im)
draw.text ((0,0), req.POST ["req_string"], font_color)
#Physical directory
path = "/file/hoge/media/test.png"
img.save (path)
# Tried a temporary directory on the way
with tempfile.NamedTemporaryFile (delete = False) as tf:
    temp_file_name = tf.name
path = "/ file/hoge/media /" + temp_file_name + "test.png"
  • Answer # 1

      

    Is there any way to save the image created on the server side in memory and display it in the browser?

    It is possible to encode the data URI and export it on HTML.

  • Answer # 2

    Pillow Image.save

      

    fp – A filename (string), pathlib.Path object or file object.

    Because it is

    , you can specify a file object instead of a file name as the first argument.

    The io module also has a file object "BytesIO" that can be read from and written to memory.
    With this combined technique, PIL can be saved in memory.

    # coding: utf-8
    import sys, io
    from PIL import Image
    if __name__ == '__main__':
        img = Image.new ('RGB', (64, 64), (0, 255, 0))
        f = io.BytesIO ()
        img.save (f, 'png')
        # Try exporting to a file for confirmation.
        with open ('hoge.png', 'wb') as out_f:
            out_f.write (f.getvalue ())

    I don't know django, so I don't know the future,

    Response that returns a Django image

    Make a response that returns an image like the one above, and specify the URL in the src attribute of the img tag.