python cv2.imread格式的图片上传到minio中并返回访问地址
时间: 2024-05-01 11:22:16 浏览: 18
首先,你需要安装 Minio Python 客户端,可以使用以下命令进行安装:
```
pip install minio
```
接下来,你需要连接到 Minio 服务器,可以使用以下代码连接:
```python
from minio import Minio
client = Minio(
"minio.example.com",
access_key="ACCESS_KEY",
secret_key="SECRET_KEY",
secure=False
)
```
在连接成功之后,你可以使用以下代码将图片上传到 Minio:
```python
import cv2
import io
# 读取图片
img = cv2.imread("test.jpg")
# 将图片转换为字节流
img_bytes = cv2.imencode(".jpg", img)[1].tostring()
# 将字节流上传到 Minio
bucket_name = "test-bucket"
object_name = "test.jpg"
client.put_object(
bucket_name=bucket_name,
object_name=object_name,
data=io.BytesIO(img_bytes),
length=len(img_bytes)
)
```
上传成功后,你可以使用以下代码获取图片的访问地址:
```python
# 获取图片访问地址
from minio.error import ResponseError
try:
url = client.presigned_get_object(bucket_name, object_name)
print(url)
except ResponseError as err:
print(err)
```
以上代码中,`presigned_get_object` 方法会返回一个带有签名的 URL,可以直接通过浏览器访问该 URL 来获取图片。