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

时间:2020-03-16 11:00:00

标签: python image azure stream

我需要将通过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")

1 个答案:

答案 0 :(得分:0)

您需要执行的操作将流的位置重置为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")