pathlib – Save BytesIO data to disk

We can save the data from a BytesIO object to the file system using the pathlib library.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from io import BytesIO
from pathlib import Path
from PIL import Image


# Path to an existing image
source_path = Path("myfiles", "images", "test.jpg")

# The thumbnail binary stream will get saved to this later.
thumbnail_binary_stream = BytesIO()

# Open image
with Image.open(source_path) as img:

    # Create thumbnail
    img.thumbnail((500, 500))

    # Save the new thumbnail to a BytesIO object.
    img.save(thumbnail_binary_stream, format="JPEG")

# The thumbnail image will get saved to this path.
thumbnail_path = Path("myfiles", "images", "test_thumbnail.jpg")

# Save the thumbnail image using the thumbnail binary stream's view
thumbnail_path.write_bytes(thumbnail_binary_stream.getbuffer())