Convert PIL Image to byte array?


1.
import
io img = Image.open(fh, mode='r') roiImg = img.crop(box) imgByteArr = io.BytesIO() roiImg.save(imgByteArr, format='PNG') imgByteArr = imgByteArr.getvalue()

 

2.
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")
3.
import
io from PIL import Image # 注意我的Image版本是pip3 install Pillow==4.3.0 import requests res = requests.get('http://images.xxx.com/-7c0dc4dbdca3.webp', stream=True) # 獲取字節流最好加stream這個參數,原因見requests官方文檔 byte_stream = io.BytesIO(res.content) # 把請求到的數據轉換為Bytes字節流(這樣解釋不知道對不對,可以參照[廖雪峰](https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431918785710e86a1a120ce04925bae155012c7fc71e000)的教程看一下) roiImg = Image.open(byte_stream) # Image打開Byte字節流數據 imgByteArr = io.BytesIO() # 創建一個空的Bytes對象 roiImg.save(imgByteArr, format='PNG') # PNG就是圖片格式,我試過換成JPG/jpg都不行 imgByteArr = imgByteArr.getvalue() # 這個就是保存的圖片字節流 # 下面這一步只是本地測試, 可以直接把imgByteArr,當成參數上傳到七牛雲 with open("./abc.png", "wb") as f: f.write(imgByteArr)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM