convert PIL Image object to File object

前端 未结 1 1902
太阳男子
太阳男子 2021-02-14 21:10

Is there any way (without saving a file to disk and then deleting it) to convert a PIL Image object to a File object?

相关标签:
1条回答
  • 2021-02-14 21:50

    Let's look at what a file object is.

    with open('test.txt', 'r') as fp:
        print(fp)
        # <_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'>
    

    https://docs.python.org/3/library/io.html has more on the subject as well.

    I suspect that for your purposes, it would be enough to have a BytesIO object.

    import io
    from PIL import Image
    im = Image.new("RGB", (100, 100))
    b = io.BytesIO()
    im.save(b, "JPEG")
    b.seek(0)
    

    But if you really want the same object, then -

    fp = io.TextIOWrapper(b)
    
    0 讨论(0)
提交回复
热议问题