从生成器对象保存图像 - Python
Save an image from a Generator object - Python
我进行了 API 调用以将图像转换为其自身的缩略图版本,并返回了一个生成器对象。但是我不知道如何将该对象保存为本地计算机上的图像。
我从 API 的文档中得到一个 "successful response contains the thumbnail image binary",但我不知道如何访问它。我在想,所以我需要将二进制文件转换为字符串或列表,然后使用 PIL?
中的图像 class 将其转换为图像
我不知道最好的方法。我知道生成器只是保存状态的迭代器,但是当涉及到其中的图像数据和访问数据以便我在本地文件夹中保存图像时,这并不意味着什么。
这是我的代码:
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
# Get a local image
local_image_path_thumb = "resources\objects.jpg"
local_image_thumb = open(local_image_path_objects, "rb")
print("Generating thumbnail from a local image...")
# Call the API with a local image, set the width/height if desired (pixels)
# Returns a Generator object, a thumbnail image binary.
thumb_local = computervision_client.generate_thumbnail_in_stream(100, 100, local_image_thumb, True)
# Save the thumbnail to your local root folder of this project.
# Save to here, somehow: "\resources\thumb_local.jpg"
print("Thumbnail saved to local folder.")
这是函数 generate_thumbnail_in_stream 的 API 文档。
with open("output_file.png", "wb") as fp:
for chunk in thumb_local:
fp.write(chunk)
我进行了 API 调用以将图像转换为其自身的缩略图版本,并返回了一个生成器对象。但是我不知道如何将该对象保存为本地计算机上的图像。
我从 API 的文档中得到一个 "successful response contains the thumbnail image binary",但我不知道如何访问它。我在想,所以我需要将二进制文件转换为字符串或列表,然后使用 PIL?
中的图像 class 将其转换为图像我不知道最好的方法。我知道生成器只是保存状态的迭代器,但是当涉及到其中的图像数据和访问数据以便我在本地文件夹中保存图像时,这并不意味着什么。
这是我的代码:
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
# Get a local image
local_image_path_thumb = "resources\objects.jpg"
local_image_thumb = open(local_image_path_objects, "rb")
print("Generating thumbnail from a local image...")
# Call the API with a local image, set the width/height if desired (pixels)
# Returns a Generator object, a thumbnail image binary.
thumb_local = computervision_client.generate_thumbnail_in_stream(100, 100, local_image_thumb, True)
# Save the thumbnail to your local root folder of this project.
# Save to here, somehow: "\resources\thumb_local.jpg"
print("Thumbnail saved to local folder.")
这是函数 generate_thumbnail_in_stream 的 API 文档。
with open("output_file.png", "wb") as fp:
for chunk in thumb_local:
fp.write(chunk)