从流将图像上载到Blob存储(Python)

2024-04-26 02:55:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我尝试过以流的形式保存它(特别是字节流),因为上传似乎也在使用流(如果这是一种幼稚的方法,很抱歉,我对Python不是很有经验),但我不知道如何在上传过程中使用它。如果使用与打开本地文件相同的方法,它将上载一个空文件

我正在使用azure存储blob版本12.2.0。我注意到,在以前版本的azure storage blob中,有可能从stream(在特定的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")

Tags: 图像imageimport版本clientstreamcontaineras
1条回答
网友
1楼 · 发布于 2024-04-26 02:55:13

您需要做的是将流的位置重置为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") 

相关问题 更多 >