程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 获取图片内容的方法

hfteth 2025-08-01 16:58:52 技术文章 6 ℃

在网络爬虫和数据处理中,获取图片内容是常见需求。Python 通过相关库可以便捷地从网络或本地获取图片内容,以下是具体实现方法及注意事项。

一、从网络获取图片内容

1.1 使用 requests 库获取

requests库是获取网络图片的常用工具,通过发送 GET 请求获取图片的字节流(二进制数据)。

import requests

def get_image_from_url(url):

try:

# 设置请求头,模拟浏览器访问

headers = {

"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"

}

# 发送GET请求,获取图片字节流

response = requests.get(url, headers=headers, timeout=10)

# 检查请求是否成功

response.raise_for_status()

# 返回图片字节内容

return response.content

except requests.exceptions.RequestException as e:

print(f"获取图片失败:{e}")

return None

# 示例:获取网络图片

image_url = "https://example.com/image.jpg"

image_content = get_image_from_url(image_url)

if image_content:

print(f"成功获取图片,大小:{len(image_content)}字节")

1.2 处理防盗链和反爬机制

部分网站会通过Referer验证防止图片盗链,此时需在请求头中添加Referer信息。

def get_image_with_referer(url, referer):

try:

headers = {

"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",

"Referer": referer # 添加Referer,模拟从该页面跳转过来的请求

}

response = requests.get(url, headers=headers, timeout=10)

response.raise_for_status()

return response.content

except requests.exceptions.RequestException as e:

print(f"获取图片失败:{e}")

return None

# 示例:带Referer获取图片

image_url = "https://example.com/protected_image.jpg"

referer_url = "
https://example.com/page_contains_image" # 图片所在的页面URL

image_content = get_image_with_referer(image_url, referer_url)

二、从本地文件获取图片内容

若图片已保存在本地,可通过文件操作读取其字节内容。

def get_image_from_local(file_path):

try:

with open(file_path, "rb") as f: # 二进制模式读取

return f.read()

except IOError as e:

print(f"读取本地图片失败:{e}")

return None

# 示例:读取本地图片

local_image_path = "local_image.png"

image_content = get_image_from_local(local_image_path)

if image_content:

print(f"成功读取本地图片,大小:{len(image_content)}字节")

三、图片内容的后续处理

获取图片内容后,可进行保存、显示或进一步处理(如压缩、识别等)。

3.1 保存图片到本地(带弹窗警告)

保存图片时,若存在同名文件,通过弹窗显示警告信息(需使用tkinter库实现图形化提示)。

import os

import tkinter as tk

from tkinter import messagebox

def save_image_with_popup(content, save_path):

# 初始化tkinter(仅用于弹窗)

root = tk.Tk()

root.withdraw() # 隐藏主窗口

# 判断图片是否已存在

if os.path.exists(save_path):

# 弹窗显示警告

messagebox.showwarning("文件已存在", f"警告:{os.path.basename(save_path)} 已存在同名图片,不再写入")

root.destroy()

return False

try:

with open(save_path, "wb") as f: # 二进制模式写入

f.write(content)

print(f"图片已保存至:{save_path}")

root.destroy()

return True

except IOError as e:

messagebox.showerror("保存失败", f"图片保存失败:{str(e)}")

root.destroy()

return False

# 示例:带弹窗警告保存图片

if image_content:

save_image_with_popup(image_content, "downloaded_image.jpg")

3.2 使用 PIL 库显示图片

需安装Pillow库(pip install pillow),可直接在程序中显示图片或进行处理。

from PIL import Image

from io import BytesIO

def show_image(content):

try:

# 将字节内容转换为图片对象

image = Image.open(BytesIO(content))

image.show() # 调用系统默认图片查看器显示

except Exception as e:

print(f"显示图片失败:{e}")

# 示例:显示获取的图片

if image_content:

show_image(image_content)

四、注意事项

  1. 弹窗依赖:tkinter是 Python 标准库,无需额外安装,但在部分服务器环境(如无图形界面的 Linux)中可能无法显示弹窗,此时可退回控制台提示。
  1. 合规性:获取网络图片时需遵守 robots 协议和网站版权声明,避免非法爬取。
  1. 异常处理:网络请求和文件操作可能出现各种异常,需通过try-except确保程序稳定性。

通过上述方法,可实现图片的获取、保存(带同名文件弹窗警告)和显示,满足不同场景下的图片处理需求。

最近发表
标签列表