【问题标题】:Upload an image to Blob Storage from a stream (in Python)从流中将图像上传到 Blob 存储(在 Python 中)
【发布时间】:2020-06-27 11:47:19
【问题描述】:

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

【问题讨论】:

    标签: python image azure stream


    【解决方案1】:

    您必须将流的位置重置为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") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-16
      • 2020-01-09
      • 2018-12-17
      • 1970-01-01
      • 2019-06-14
      • 2019-05-26
      • 2013-07-29
      • 2020-01-25
      相关资源
      最近更新 更多