2017-05-28 53 views
1

壓縮圖像字節表示我怎樣才能得到同樣的效果:獲取內存

from PIL import Image 
with Image.open(image_path) as image: 
    image.thumbnail((200, 200), Image.ANTIALIAS) 
    image.save(temporary_thumbnail_path) 
with open(temporary_thumbnail_path, "rb") as thumbnail_file: 
    thumbnail_as_string = base64.b64encode(thumbnail_file.read()).decode() 

,而不必寫入磁盤?

即我想獲得壓縮的圖像的字節表示,但不必訴諸於temporary_thumbnail_path。 我知道PIL文檔建議使用

save(),帶有用於內存數據的BytesIO參數。

但我不確定明白這是什麼意思,並沒有在網上找到例子。

回答

1

也沒那麼難:

import io 
from PIL import Image 

output = io.BytesIO() 
with Image.open(image_path) as image: 
    image.thumbnail((400, 400), Image.ANTIALIAS) 
    image.save(output, format="JPEG") 
    thumbnail_as_string = base64.b64encode(output.getvalue()).decode()