Pillow: How to output a binary byte stream of a picture

Created on 19 Jun 2018  Â·  2Comments  Â·  Source: python-pillow/Pillow

I want to implement an online turn format function, When you input the URL of a picture and the specified suffix, you can return the finished binary data.
Like this:
_jpg_bin = my_func("http://p1.pstatp.com/list/300x196/pgc-image/152923179745640a81b1fdc.webp", "jpg)_
But I've been looking at pillow documents for a long time without seeing the way to output binary, basically "save" ("file path.Jpg"), and I also try to see the source code of the save method, but I don't have a very good Python base.

Most helpful comment

from PIL import Image
import io

# I don't know what Python version you're using, so I'll try using Python 3 first
try:
    import urllib.request as urllib
except ImportError:
    # You are using Python 2 it turns out
    import urllib

def my_func(filename, ext):
    # Get the image from the URL
    im = Image.open(urllib.urlopen(filename))

    fp = io.BytesIO()
    format = Image.registered_extensions()['.'+ext]
    im.save(fp, format)
    return fp.getvalue()

jpg_bin = my_func("http://p1.pstatp.com/list/300x196/pgc-image/152923179745640a81b1fdc.webp", "jpg")

All 2 comments

from PIL import Image
import io

# I don't know what Python version you're using, so I'll try using Python 3 first
try:
    import urllib.request as urllib
except ImportError:
    # You are using Python 2 it turns out
    import urllib

def my_func(filename, ext):
    # Get the image from the URL
    im = Image.open(urllib.urlopen(filename))

    fp = io.BytesIO()
    format = Image.registered_extensions()['.'+ext]
    im.save(fp, format)
    return fp.getvalue()

jpg_bin = my_func("http://p1.pstatp.com/list/300x196/pgc-image/152923179745640a81b1fdc.webp", "jpg")

Very thanks your help, I found the answer on stackoverflow yesterday, https://stackoverflow.com/questions/33101935/convert-pil-image-to-byte-array
But I'm still very grateful to you。

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Larivact picture Larivact  Â·  4Comments

maxhumber picture maxhumber  Â·  3Comments

vytisb picture vytisb  Â·  4Comments

indirectlylit picture indirectlylit  Â·  4Comments

nomarek picture nomarek  Â·  3Comments