简体   繁体   中英

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. But I don't know how to save that object as an image on my local machine.

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. 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?

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.

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 .

with open("output_file.png", "wb") as fp:
    for chunk in thumb_local:
        fp.write(chunk)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM