gpt4 book ai didi

python - 将图像从流上传到 Blob 存储(在 Python 中)

转载 作者:行者123 更新时间:2023-12-05 02:08:36 26 4
gpt4 key购买 nike

我需要将 Python 生成的图像上传到 Azure Blob 存储,而不将其保存在本地。此时,我生成了一个图像,将其保存在本地并将其上传到存储(请参见下面的代码),但我需要为大量图像运行它,并且需要它不依赖于本地存储。

我尝试以流的形式保存它(特别是字节流),因为上传似乎也在使用流(抱歉,如果这是一种幼稚的方法,我在Python方面没有那么丰富的经验),但我不知道如何在上传过程中使用它。如果我像打开本地文件一样使用它,它会上传一个空文件。

我正在使用 azure-storage-blob 版本 12.2.0。我注意到,在以前版本的 azure-storage-blob 中,可以从流上传(特别是 BlockBlobService.get_blob_to_stream),但我在这个版本中找不到它,并且由于某些依赖项,我无法降级包。

非常感谢任何帮助。

import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
from azure.storage.blob import ContainerClient

# create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.sin(2 * np.pi * t)

# plot it
fig, ax1 = plt.subplots()
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp')
ax1.plot(t, data1)

# save it locally
plt.savefig("example.png")

# create a blob client and upload the file
container_client = ContainerClient.from_container_url(container_SASconnection_string)
blob_client = container_client.get_blob_client(blob = "example.png")

with open("example.png") as data:
blob_client.upload_blob(data, blob_type="BlockBlob")


# ALTERNATIVELY, instead of saving locally save it as an image stream
fig, ax1 = plt.subplots()
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp')
ax1.plot(t, data1)

image_stream = BytesIO()
plt.savefig(image_stream)

# but this does not work (it uploads an empty file)
# blob_client.upload_blob(image_stream, blob_type="BlockBlob")

最佳答案

您必须将流的位置重置为 0,然后您可以将其直接上传到 Blob 存储,而无需先将其保存到本地文件。

这是我编写的代码:

import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
from azure.storage.blob import ContainerClient

# create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.sin(2 * np.pi * t)

# plot it
fig, ax1 = plt.subplots()
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp')
ax1.plot(t, data1)

image_stream = BytesIO()
plt.savefig(image_stream)
# reset stream's position to 0
image_stream.seek(0)

# upload in blob storage
container_client = ContainerClient.from_container_url(container_SASconnection_string)
blob_client = container_client.get_blob_client(blob = "example.png")
blob_client.upload_blob(image_stream.read(), blob_type="BlockBlob")

关于python - 将图像从流上传到 Blob 存储(在 Python 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60704712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com