or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

area-of-interest.mddomain-analysis.mdimage-analysis.mdimage-description.mdimage-tagging.mdindex.mdobject-detection.mdocr-text-recognition.mdthumbnail-generation.md

thumbnail-generation.mddocs/

0

# Thumbnail Generation

1

2

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.

3

4

## Capabilities

5

6

### Smart Thumbnail Generation

7

8

Create thumbnails with intelligent cropping that preserves the most important visual content of the original image.

9

10

```python { .api }

11

def generate_thumbnail(width, height, url, smart_cropping=None, model_version="latest", custom_headers=None, raw=False, **operation_config):

12

"""

13

Generate thumbnail image with optional smart cropping.

14

15

Args:

16

width (int): Thumbnail width in pixels (16-1024)

17

height (int): Thumbnail height in pixels (16-1024)

18

url (str): Publicly reachable URL of source image

19

smart_cropping (bool, optional): Enable smart cropping algorithm to preserve important content.

20

Default: True if not specified

21

model_version (str, optional): AI model version. Default: "latest"

22

custom_headers (dict, optional): Custom HTTP headers

23

raw (bool, optional): Return raw response. Default: False

24

25

Returns:

26

Generator: Binary image data stream (JPEG format)

27

28

Raises:

29

ComputerVisionErrorResponseException: API error occurred

30

31

Note:

32

The returned stream contains binary image data that can be saved directly to a file

33

or processed further. The output format is always JPEG.

34

"""

35

36

def generate_thumbnail_in_stream(width, height, image, smart_cropping=None, model_version="latest", custom_headers=None, raw=False, **operation_config):

37

"""

38

Generate thumbnail from binary image stream.

39

40

Args:

41

width (int): Thumbnail width in pixels

42

height (int): Thumbnail height in pixels

43

image (Generator): Binary source image data stream

44

smart_cropping (bool, optional): Enable smart cropping algorithm

45

46

Returns:

47

Generator: Binary thumbnail image data stream

48

"""

49

```

50

51

## Usage Examples

52

53

### Basic Thumbnail Generation

54

55

```python

56

from azure.cognitiveservices.vision.computervision import ComputerVisionClient

57

from msrest.authentication import CognitiveServicesCredentials

58

59

# Initialize client

60

credentials = CognitiveServicesCredentials("your-api-key")

61

client = ComputerVisionClient("https://your-endpoint.cognitiveservices.azure.com/", credentials)

62

63

# Generate thumbnail with smart cropping

64

image_url = "https://example.com/large-photo.jpg"

65

thumbnail_width = 200

66

thumbnail_height = 200

67

68

thumbnail_stream = client.generate_thumbnail(

69

width=thumbnail_width,

70

height=thumbnail_height,

71

url=image_url,

72

smart_cropping=True

73

)

74

75

# Save thumbnail to file

76

with open("thumbnail.jpg", "wb") as thumb_file:

77

for chunk in thumbnail_stream:

78

thumb_file.write(chunk)

79

80

print(f"Thumbnail saved: {thumbnail_width}x{thumbnail_height} pixels")

81

```

82

83

### Multiple Thumbnail Sizes

84

85

```python

86

# Generate multiple thumbnail sizes for responsive design

87

image_url = "https://example.com/high-res-image.jpg"

88

89

thumbnail_sizes = [

90

(150, 150), # Small square

91

(300, 200), # Medium rectangle

92

(500, 300), # Large banner

93

(100, 150), # Portrait

94

(150, 100) # Landscape

95

]

96

97

for i, (width, height) in enumerate(thumbnail_sizes):

98

try:

99

thumbnail_stream = client.generate_thumbnail(

100

width=width,

101

height=height,

102

url=image_url,

103

smart_cropping=True

104

)

105

106

filename = f"thumbnail_{width}x{height}.jpg"

107

with open(filename, "wb") as thumb_file:

108

for chunk in thumbnail_stream:

109

thumb_file.write(chunk)

110

111

print(f"Generated: {filename}")

112

113

except Exception as e:

114

print(f"Failed to generate {width}x{height} thumbnail: {e}")

115

```

116

117

### Smart Cropping vs. Standard Resizing

118

119

```python

120

# Compare smart cropping with standard resizing

121

image_url = "https://example.com/portrait-photo.jpg"

122

width, height = 300, 300

123

124

# Generate with smart cropping enabled

125

smart_thumbnail = client.generate_thumbnail(

126

width=width,

127

height=height,

128

url=image_url,

129

smart_cropping=True

130

)

131

132

with open("smart_cropped_thumbnail.jpg", "wb") as f:

133

for chunk in smart_thumbnail:

134

f.write(chunk)

135

136

# Generate with smart cropping disabled (standard resize)

137

standard_thumbnail = client.generate_thumbnail(

138

width=width,

139

height=height,

140

url=image_url,

141

smart_cropping=False

142

)

143

144

with open("standard_thumbnail.jpg", "wb") as f:

145

for chunk in standard_thumbnail:

146

f.write(chunk)

147

148

print("Compare smart_cropped_thumbnail.jpg vs standard_thumbnail.jpg")

149

print("Smart cropping preserves important content, standard may distort")

150

```

151

152

### Local File Thumbnail Generation

153

154

```python

155

# Generate thumbnail from local image file

156

local_image_path = "vacation_photo.jpg"

157

158

with open(local_image_path, "rb") as image_stream:

159

thumbnail_stream = client.generate_thumbnail_in_stream(

160

width=250,

161

height=250,

162

image=image_stream,

163

smart_cropping=True

164

)

165

166

# Save the thumbnail

167

with open("vacation_thumbnail.jpg", "wb") as thumb_file:

168

for chunk in thumbnail_stream:

169

thumb_file.write(chunk)

170

171

print("Local image thumbnail generated")

172

```

173

174

### Batch Thumbnail Processing

175

176

```python

177

import os

178

from pathlib import Path

179

180

# Process multiple images for thumbnails

181

image_urls = [

182

"https://example.com/photo1.jpg",

183

"https://example.com/photo2.jpg",

184

"https://example.com/photo3.jpg"

185

]

186

187

thumbnail_dir = Path("thumbnails")

188

thumbnail_dir.mkdir(exist_ok=True)

189

190

thumbnail_size = (200, 200)

191

192

for i, url in enumerate(image_urls):

193

try:

194

thumbnail_stream = client.generate_thumbnail(

195

width=thumbnail_size[0],

196

height=thumbnail_size[1],

197

url=url,

198

smart_cropping=True

199

)

200

201

# Save with numbered filename

202

output_path = thumbnail_dir / f"thumb_{i+1:03d}.jpg"

203

with open(output_path, "wb") as thumb_file:

204

for chunk in thumbnail_stream:

205

thumb_file.write(chunk)

206

207

print(f"Generated thumbnail: {output_path}")

208

209

except Exception as e:

210

print(f"Failed to process {url}: {e}")

211

212

print(f"Batch processing complete. Thumbnails saved to {thumbnail_dir}/")

213

```

214

215

### Responsive Thumbnail Gallery

216

217

```python

218

# Generate thumbnails for a responsive web gallery

219

image_url = "https://example.com/gallery-image.jpg"

220

221

# Define responsive breakpoints

222

responsive_sizes = {

223

'xs': (150, 150), # Extra small screens

224

'sm': (200, 200), # Small screens

225

'md': (300, 200), # Medium screens

226

'lg': (400, 300), # Large screens

227

'xl': (500, 350) # Extra large screens

228

}

229

230

gallery_thumbs = {}

231

232

for breakpoint, (width, height) in responsive_sizes.items():

233

try:

234

thumbnail_stream = client.generate_thumbnail(

235

width=width,

236

height=height,

237

url=image_url,

238

smart_cropping=True

239

)

240

241

filename = f"gallery_{breakpoint}_{width}x{height}.jpg"

242

with open(filename, "wb") as thumb_file:

243

for chunk in thumbnail_stream:

244

thumb_file.write(chunk)

245

246

gallery_thumbs[breakpoint] = {

247

'filename': filename,

248

'width': width,

249

'height': height

250

}

251

252

print(f"Generated {breakpoint}: {filename}")

253

254

except Exception as e:

255

print(f"Failed to generate {breakpoint} thumbnail: {e}")

256

257

# Generate HTML for responsive images

258

html_template = '''

259

<picture>

260

<source media="(min-width: 1200px)" srcset="{xl}">

261

<source media="(min-width: 992px)" srcset="{lg}">

262

<source media="(min-width: 768px)" srcset="{md}">

263

<source media="(min-width: 576px)" srcset="{sm}">

264

<img src="{xs}" alt="Gallery image" style="width: 100%; height: auto;">

265

</picture>

266

'''

267

268

if len(gallery_thumbs) == 5: # All sizes generated successfully

269

html = html_template.format(**{bp: info['filename'] for bp, info in gallery_thumbs.items()})

270

with open("responsive_gallery.html", "w") as f:

271

f.write(html)

272

print("Responsive HTML gallery code saved to responsive_gallery.html")

273

```

274

275

### Quality and Size Analysis

276

277

```python

278

import os

279

280

# Analyze thumbnail file sizes for different dimensions

281

image_url = "https://example.com/test-image.jpg"

282

test_sizes = [(100, 100), (200, 200), (400, 400), (800, 600)]

283

284

print("Thumbnail size analysis:")

285

print("Dimensions\tFile Size\tSmart Crop")

286

287

for width, height in test_sizes:

288

# Smart cropping enabled

289

smart_thumb = client.generate_thumbnail(width, height, image_url, smart_cropping=True)

290

smart_filename = f"test_smart_{width}x{height}.jpg"

291

292

with open(smart_filename, "wb") as f:

293

for chunk in smart_thumb:

294

f.write(chunk)

295

296

smart_size = os.path.getsize(smart_filename)

297

298

# Smart cropping disabled

299

standard_thumb = client.generate_thumbnail(width, height, image_url, smart_cropping=False)

300

standard_filename = f"test_standard_{width}x{height}.jpg"

301

302

with open(standard_filename, "wb") as f:

303

for chunk in standard_thumb:

304

f.write(chunk)

305

306

standard_size = os.path.getsize(standard_filename)

307

308

print(f"{width}x{height}\t\t{smart_size:,} bytes\tYes")

309

print(f"{width}x{height}\t\t{standard_size:,} bytes\tNo")

310

311

# Clean up test files

312

os.remove(smart_filename)

313

os.remove(standard_filename)

314

```

315

316

## Smart Cropping Algorithm

317

318

### How Smart Cropping Works

319

320

Smart cropping uses computer vision algorithms to:

321

322

1. **Identify Important Regions**: Analyze the image to find areas with high visual interest

323

2. **Face Detection**: Prioritize human faces in the composition

324

3. **Object Recognition**: Consider important objects and their spatial relationships

325

4. **Visual Saliency**: Focus on areas that naturally draw viewer attention

326

5. **Composition Rules**: Apply photographic composition principles

327

328

### When to Use Smart Cropping

329

330

**Enable Smart Cropping (True) when:**

331

- Creating profile pictures or avatars

332

- Generating thumbnails for articles or blog posts

333

- Building image galleries where content preservation matters

334

- Working with photos containing people or important subjects

335

- Creating social media preview images

336

337

**Disable Smart Cropping (False) when:**

338

- You want exact aspect ratio matching regardless of content loss

339

- Working with abstract patterns or textures where any crop is acceptable

340

- Generating thumbnails for decorative purposes

341

- Processing images where uniform scaling is more important than content

342

343

### Size Limitations

344

345

- **Minimum size**: 16x16 pixels

346

- **Maximum size**: 1024x1024 pixels

347

- **Supported ratios**: Any aspect ratio within size constraints

348

- **Output format**: Always JPEG

349

350

### Performance Considerations

351

352

- Smart cropping adds minimal processing time (typically <1 second)

353

- File size depends on content complexity and dimensions

354

- Larger thumbnails provide better quality but larger file sizes

355

- Consider generating multiple sizes for responsive design