File tree Expand file tree Collapse file tree 1 file changed +52
-6
lines changed Expand file tree Collapse file tree 1 file changed +52
-6
lines changed Original file line number Diff line number Diff line change @@ -13,18 +13,16 @@ gitChangelog: false
1313
1414## 方式1-图片 url 传入
1515
16- ::: warning
17- ** 请确保该图片的链接访问权限是公开的** 。
18- :::
16+ > [ !WARNING]
17+ > ** 请确保该图片的链接访问权限是公开的** 。
1918
2019常见模型均支持以图片 url 传入,可以通过将图片上传到图床等方式获取图片 url 链接,以字符串的方式传入,模型侧会访问该 url 并下载图片分析。
2120
2221
2322## 方式2-图片 base64 编码传入
2423
25- ::: tip
26- Base64 编码常用于本地上传图片的场景。
27- :::
24+ > [ !TIP]
25+ > Base64 编码常用于本地上传图片的场景。
2826
2927` Base64 ` 编码是将数据用 64 个可打印的字符进行编码的方式,任何数据底层实现都是二进制,因此都可以使用 ` Base64 ` 编码,在网络数据传输过程中图片通常使用 ` Base64 ` 编码。` Base64 ` 编码可用于在HTTP环境下传递较长的标识信息。
3028
@@ -48,3 +46,51 @@ def get_image_base64(image_path):
4846base64array = get_image_base64("/Users/your_image.png") # 修改为你的图片绝对路径
4947print(base64array)
5048```
49+
50+ ## 方式3-将 url 图片获取为 base64 编码
51+
52+ > [ !TIP]
53+ > 需要确保访问的图片链接是公开的并且** 没有网络代理方面的问题** 。
54+
55+ 可以通过网络请求直接读取图片内容并且转换为 base64 编码,以下为示例代码:
56+
57+ ### 常用函数
58+
59+ ``` python[python]
60+ import requests
61+ import base64
62+ from io import BytesIO
63+
64+ def url_image_to_base64(image_url):
65+ """
66+ 从URL获取图片并转换为base64格式
67+
68+ 参数:
69+ image_url (str): 图片的URL地址
70+
71+ 返回:
72+ str: base64编码的图片字符串
73+ """
74+ try:
75+ # 发送GET请求获取图片
76+ response = requests.get(image_url)
77+
78+ # 检查请求是否成功
79+ response.raise_for_status()
80+
81+ # 将图片内容编码为base64
82+ image_binary = response.content
83+ base64_encoded = base64.b64encode(image_binary).decode('utf-8')
84+
85+ return base64_encoded
86+
87+ except Exception as e:
88+ print(f"获取图片失败: {str(e)}")
89+ return None
90+
91+ # 使用示例
92+ if __name__ == "__main__":
93+ url = "https://cdn.klingai.com/bs2/upload-kling-api/8089468206/image/Cl6kH2gHPegAAAAABUwweg-0_raw_image_0.png"
94+ base64_string = url_image_to_base64(url)
95+ print(base64_string)
96+ ```
You can’t perform that action at this time.
0 commit comments