Microsoft Azure Cognitive Services Computer Vision Client Library for Python providing state-of-the-art algorithms to process images and return information including mature content detection, face detection, color analysis, image categorization, description generation, and thumbnail creation.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Generate intelligent thumbnails with smart cropping to preserve important image content. The service creates optimally sized thumbnails that maintain the most visually important parts of the original image.
Create thumbnails with intelligent cropping that preserves the most important visual content of the original image.
def generate_thumbnail(width, height, url, smart_cropping=None, model_version="latest", custom_headers=None, raw=False, **operation_config):
"""
Generate thumbnail image with optional smart cropping.
Args:
width (int): Thumbnail width in pixels (16-1024)
height (int): Thumbnail height in pixels (16-1024)
url (str): Publicly reachable URL of source image
smart_cropping (bool, optional): Enable smart cropping algorithm to preserve important content.
Default: True if not specified
model_version (str, optional): AI model version. Default: "latest"
custom_headers (dict, optional): Custom HTTP headers
raw (bool, optional): Return raw response. Default: False
Returns:
Generator: Binary image data stream (JPEG format)
Raises:
ComputerVisionErrorResponseException: API error occurred
Note:
The returned stream contains binary image data that can be saved directly to a file
or processed further. The output format is always JPEG.
"""
def generate_thumbnail_in_stream(width, height, image, smart_cropping=None, model_version="latest", custom_headers=None, raw=False, **operation_config):
"""
Generate thumbnail from binary image stream.
Args:
width (int): Thumbnail width in pixels
height (int): Thumbnail height in pixels
image (Generator): Binary source image data stream
smart_cropping (bool, optional): Enable smart cropping algorithm
Returns:
Generator: Binary thumbnail image data stream
"""from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from msrest.authentication import CognitiveServicesCredentials
# Initialize client
credentials = CognitiveServicesCredentials("your-api-key")
client = ComputerVisionClient("https://your-endpoint.cognitiveservices.azure.com/", credentials)
# Generate thumbnail with smart cropping
image_url = "https://example.com/large-photo.jpg"
thumbnail_width = 200
thumbnail_height = 200
thumbnail_stream = client.generate_thumbnail(
width=thumbnail_width,
height=thumbnail_height,
url=image_url,
smart_cropping=True
)
# Save thumbnail to file
with open("thumbnail.jpg", "wb") as thumb_file:
for chunk in thumbnail_stream:
thumb_file.write(chunk)
print(f"Thumbnail saved: {thumbnail_width}x{thumbnail_height} pixels")# Generate multiple thumbnail sizes for responsive design
image_url = "https://example.com/high-res-image.jpg"
thumbnail_sizes = [
(150, 150), # Small square
(300, 200), # Medium rectangle
(500, 300), # Large banner
(100, 150), # Portrait
(150, 100) # Landscape
]
for i, (width, height) in enumerate(thumbnail_sizes):
try:
thumbnail_stream = client.generate_thumbnail(
width=width,
height=height,
url=image_url,
smart_cropping=True
)
filename = f"thumbnail_{width}x{height}.jpg"
with open(filename, "wb") as thumb_file:
for chunk in thumbnail_stream:
thumb_file.write(chunk)
print(f"Generated: {filename}")
except Exception as e:
print(f"Failed to generate {width}x{height} thumbnail: {e}")# Compare smart cropping with standard resizing
image_url = "https://example.com/portrait-photo.jpg"
width, height = 300, 300
# Generate with smart cropping enabled
smart_thumbnail = client.generate_thumbnail(
width=width,
height=height,
url=image_url,
smart_cropping=True
)
with open("smart_cropped_thumbnail.jpg", "wb") as f:
for chunk in smart_thumbnail:
f.write(chunk)
# Generate with smart cropping disabled (standard resize)
standard_thumbnail = client.generate_thumbnail(
width=width,
height=height,
url=image_url,
smart_cropping=False
)
with open("standard_thumbnail.jpg", "wb") as f:
for chunk in standard_thumbnail:
f.write(chunk)
print("Compare smart_cropped_thumbnail.jpg vs standard_thumbnail.jpg")
print("Smart cropping preserves important content, standard may distort")# Generate thumbnail from local image file
local_image_path = "vacation_photo.jpg"
with open(local_image_path, "rb") as image_stream:
thumbnail_stream = client.generate_thumbnail_in_stream(
width=250,
height=250,
image=image_stream,
smart_cropping=True
)
# Save the thumbnail
with open("vacation_thumbnail.jpg", "wb") as thumb_file:
for chunk in thumbnail_stream:
thumb_file.write(chunk)
print("Local image thumbnail generated")import os
from pathlib import Path
# Process multiple images for thumbnails
image_urls = [
"https://example.com/photo1.jpg",
"https://example.com/photo2.jpg",
"https://example.com/photo3.jpg"
]
thumbnail_dir = Path("thumbnails")
thumbnail_dir.mkdir(exist_ok=True)
thumbnail_size = (200, 200)
for i, url in enumerate(image_urls):
try:
thumbnail_stream = client.generate_thumbnail(
width=thumbnail_size[0],
height=thumbnail_size[1],
url=url,
smart_cropping=True
)
# Save with numbered filename
output_path = thumbnail_dir / f"thumb_{i+1:03d}.jpg"
with open(output_path, "wb") as thumb_file:
for chunk in thumbnail_stream:
thumb_file.write(chunk)
print(f"Generated thumbnail: {output_path}")
except Exception as e:
print(f"Failed to process {url}: {e}")
print(f"Batch processing complete. Thumbnails saved to {thumbnail_dir}/")# Generate thumbnails for a responsive web gallery
image_url = "https://example.com/gallery-image.jpg"
# Define responsive breakpoints
responsive_sizes = {
'xs': (150, 150), # Extra small screens
'sm': (200, 200), # Small screens
'md': (300, 200), # Medium screens
'lg': (400, 300), # Large screens
'xl': (500, 350) # Extra large screens
}
gallery_thumbs = {}
for breakpoint, (width, height) in responsive_sizes.items():
try:
thumbnail_stream = client.generate_thumbnail(
width=width,
height=height,
url=image_url,
smart_cropping=True
)
filename = f"gallery_{breakpoint}_{width}x{height}.jpg"
with open(filename, "wb") as thumb_file:
for chunk in thumbnail_stream:
thumb_file.write(chunk)
gallery_thumbs[breakpoint] = {
'filename': filename,
'width': width,
'height': height
}
print(f"Generated {breakpoint}: {filename}")
except Exception as e:
print(f"Failed to generate {breakpoint} thumbnail: {e}")
# Generate HTML for responsive images
html_template = '''
<picture>
<source media="(min-width: 1200px)" srcset="{xl}">
<source media="(min-width: 992px)" srcset="{lg}">
<source media="(min-width: 768px)" srcset="{md}">
<source media="(min-width: 576px)" srcset="{sm}">
<img src="{xs}" alt="Gallery image" style="width: 100%; height: auto;">
</picture>
'''
if len(gallery_thumbs) == 5: # All sizes generated successfully
html = html_template.format(**{bp: info['filename'] for bp, info in gallery_thumbs.items()})
with open("responsive_gallery.html", "w") as f:
f.write(html)
print("Responsive HTML gallery code saved to responsive_gallery.html")import os
# Analyze thumbnail file sizes for different dimensions
image_url = "https://example.com/test-image.jpg"
test_sizes = [(100, 100), (200, 200), (400, 400), (800, 600)]
print("Thumbnail size analysis:")
print("Dimensions\tFile Size\tSmart Crop")
for width, height in test_sizes:
# Smart cropping enabled
smart_thumb = client.generate_thumbnail(width, height, image_url, smart_cropping=True)
smart_filename = f"test_smart_{width}x{height}.jpg"
with open(smart_filename, "wb") as f:
for chunk in smart_thumb:
f.write(chunk)
smart_size = os.path.getsize(smart_filename)
# Smart cropping disabled
standard_thumb = client.generate_thumbnail(width, height, image_url, smart_cropping=False)
standard_filename = f"test_standard_{width}x{height}.jpg"
with open(standard_filename, "wb") as f:
for chunk in standard_thumb:
f.write(chunk)
standard_size = os.path.getsize(standard_filename)
print(f"{width}x{height}\t\t{smart_size:,} bytes\tYes")
print(f"{width}x{height}\t\t{standard_size:,} bytes\tNo")
# Clean up test files
os.remove(smart_filename)
os.remove(standard_filename)Smart cropping uses computer vision algorithms to:
Enable Smart Cropping (True) when:
Disable Smart Cropping (False) when:
Install with Tessl CLI
npx tessl i tessl/pypi-azure-cognitiveservices-vision-computervision