首頁 > 後端開發 > Python教學 > 如何在 Python 中將 Web URL 中的圖片載入到 PIL 物件中?

如何在 Python 中將 Web URL 中的圖片載入到 PIL 物件中?

Susan Sarandon
發布: 2024-11-15 14:35:03
原創
529 人瀏覽過

How to Load Images from Web URLs into PIL Objects in Python?

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板