Reading Image Data from Web URLs in Python
Retrieving image data from a local file using the Python Imaging Library (PIL) is straightforward. However, challenges arise when accessing images hosted on remote URLs. This article will provide a solution for efficiently creating PIL image objects from URL sources, eliminating the need for storing intermediate files.
The primary issue with using Image.open(urlopen(url)) is the unavailability of the seek() method for file-like objects. To address this, one might attempt Image.open(urlopen(url).read()), but this approach also fails.
Fortunately, there exists a viable solution in Python 3. By utilizing the BytesIO class from the io module, you can work directly with the image data retrieved from the URL. Here's how you can achieve this:
from PIL import Image import requests from io import BytesIO response = requests.get(url) img = Image.open(BytesIO(response.content))
This snippet first uses the requests library to fetch the image data from the specified URL. The BytesIO class then wraps the raw content into a file-like object that can be directly passed to Image.open(), creating a PIL image object.
By leveraging this approach, you can efficiently load image data from URLs without the need for creating temporary files, streamlining your image processing workflows.
以上是如何在 Python 中將 Web URL 中的圖片載入到 PIL 物件中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!