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

Ver*_*ana 3 python image stream azure

我需要将 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")
Run Code Online (Sandbox Code Playgroud)

Gau*_*tri 5

您必须执行的操作是将流的位置重置为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") 
Run Code Online (Sandbox Code Playgroud)