D
D
Dmitry2021-07-31 15:01:27
Python
Dmitry, 2021-07-31 15:01:27

Selenium how to save an image to an object?

Good day, dear ones. I'm working on a personal project and I need to save an image to a variable. Now I will give my code and try to explain everything as accurately as possible.

# я получаю src картинки через selenium, он хранится в переменной image_src
# теперь я получаю байты картинки через requests, если есть способ лучше - you are welcome
img_bytes = bytes(requests.get(image_src).content)
# и теперь я хочу сохранить эти байты как объект картинки, например PIL.Image
# но тут неполадка
# если я использую save_func, всё работает и файл появляется в директории проекта, но
# Show_as_Image не отрабатывает с сообщением not enough image data

def save_func(image_bytes):
    # path хранит в себе путь к директории проекта и задан выше
    with open(f"{path}\\image.jpg", "wb") as file:
        file.write(image)

def Show_as_Image(image_bytes):
    # from PIL import Image в начале кода
    # browser is webdriver.Chrome если так важно
    w, h = get_resolution(browser) # возвращает верное разрешение изображения, нас не интересует как оно работает
    image_obj = Image.frombytes("RGB", (w, h), image_bytes) # ошибка на этой строчке:
    # ValueError: not enough image data
    image_obj.show()


How do I convert my bytes into an image object if I don't want to make a bike like:
save_func(image_bytes)
img = Image.open(f"{path}\\image.jpg")

?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-07-31
@ODNik

Because you don't understand what from_bytes() does.

Creates a copy of an image memory from pixel data in a buffer.
In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data ).

It requires an array of pixel values, not the contents in a graphic format file.
Use Image.open() . By the way, open() takes as input not only a path to a file, but also a file-like object. This opens up two possibilities:
1. Use the io.BytesIO class to store data in memory instead of a temporary file.
2. Feed the PIL server response using .raw instead of .content.
The second option is preferable, since it does not require the entire image to be cached in memory, but you need to check its performance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question