[英]Save an image from a Generator object - Python
I made an API call to convert an image into a thumbnail version of itself, and that returned a Generator object.我调用了 API 将图像转换为自身的缩略图版本,并返回了生成器 object。 But I don't know how to save that object as an image on my local machine.
但我不知道如何将 object 保存为本地计算机上的图像。
I get from the documentation of the API that a "successful response contains the thumbnail image binary", but I don't know how to access it.我从 API 的文档中得到“成功的响应包含缩略图二进制文件”,但我不知道如何访问它。 I was thinking, so I need to convert the binary into a string or list and then convert that into an image by using the Image class from PIL?
我在想,所以我需要将二进制文件转换为字符串或列表,然后使用 PIL 的 Image class 将其转换为图像?
I don't know the best way to do it.我不知道最好的方法。 I know Generators are just iterators that save state, but that doesn't mean much when it comes to image data being in it and accessing the data so that I have a saved image in my local folder.
我知道生成器只是保存 state 的迭代器,但这对于其中的图像数据和访问数据而言意义不大,因此我在本地文件夹中有一个保存的图像。
Here is my code:这是我的代码:
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.")
Here is the API documentation for the function generate_thumbnail_in_stream .这是 function generate_thumbnail_in_stream的 API 文档。
with open("output_file.png", "wb") as fp:
for chunk in thumb_local:
fp.write(chunk)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.