or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-integration.mdenumerations.mdimage-creation.mdimage-operations.mdimage-output.mdindex.mdio-connections.mdproperties-metadata.mdsystem-control.md

image-output.mddocs/

0

# Image Output

1

2

Methods for saving and exporting images to files, memory buffers, and custom targets. PyVips supports all major output formats with extensive format-specific options and optimization capabilities.

3

4

## Capabilities

5

6

### File Output

7

8

Save images to filesystem with automatic format detection and comprehensive format options.

9

10

```python { .api }

11

def write_to_file(self, vips_filename: str, **kwargs) -> None:

12

"""

13

Write image to file.

14

15

Parameters:

16

- vips_filename: str, output file path (format auto-detected from extension)

17

- Q: int, quality (1-100 for JPEG, WebP)

18

- compression: str/int, compression type/level

19

- strip: bool, remove metadata

20

- optimize: bool, optimize file size

21

- progressive: bool, progressive encoding

22

- Format-specific options vary by file type

23

24

Returns:

25

None (writes to disk)

26

"""

27

```

28

29

Example usage:

30

31

```python

32

# Basic file save (format from extension)

33

image.write_to_file('output.jpg')

34

image.write_to_file('output.png')

35

image.write_to_file('output.webp')

36

37

# JPEG with quality and optimization

38

image.write_to_file('photo.jpg', Q=95, optimize=True, progressive=True)

39

40

# PNG with compression

41

image.write_to_file('image.png', compression=9, strip=True)

42

43

# TIFF with specific compression

44

image.write_to_file('data.tiff', compression='lzw', tile=True)

45

46

# WebP with quality and lossless option

47

image.write_to_file('modern.webp', Q=80, lossless=False, strip=True)

48

```

49

50

### Buffer Output

51

52

Write images to memory buffers for network transmission, further processing, or embedding.

53

54

```python { .api }

55

def write_to_buffer(self, format_string: str, **kwargs) -> bytes:

56

"""

57

Write image to memory buffer.

58

59

Parameters:

60

- format_string: str, output format ('.jpg', '.png', '.webp', etc.)

61

- Same format-specific options as write_to_file

62

63

Returns:

64

bytes object containing encoded image data

65

"""

66

```

67

68

Example usage:

69

70

```python

71

# Basic buffer output

72

jpeg_data = image.write_to_buffer('.jpg')

73

png_data = image.write_to_buffer('.png')

74

75

# High-quality JPEG

76

jpeg_data = image.write_to_buffer('.jpg', Q=95, optimize=True)

77

78

# Compressed PNG

79

png_data = image.write_to_buffer('.png', compression=9)

80

81

# WebP with options

82

webp_data = image.write_to_buffer('.webp', Q=80, lossless=False)

83

84

# Use buffer data

85

import requests

86

files = {'image': ('photo.jpg', jpeg_data, 'image/jpeg')}

87

response = requests.post('https://api.example.com/upload', files=files)

88

89

# Save buffer to file

90

with open('output.jpg', 'wb') as f:

91

f.write(jpeg_data)

92

```

93

94

### Target Output

95

96

Write images to Target objects for advanced I/O scenarios and streaming operations.

97

98

```python { .api }

99

def write_to_target(self, target: 'Target', format_string: str, **kwargs) -> None:

100

"""

101

Write image to Target object.

102

103

Parameters:

104

- target: Target object for output

105

- format_string: str, output format

106

- Same format-specific options as write_to_file

107

108

Returns:

109

None (writes to target)

110

"""

111

```

112

113

Example usage:

114

115

```python

116

# Write to file target

117

target = pyvips.Target.new_to_file('output.jpg')

118

image.write_to_target(target, '.jpg', Q=90)

119

120

# Write to memory target

121

target = pyvips.Target.new_to_memory()

122

image.write_to_target(target, '.png', compression=6)

123

buffer_data = target.get()

124

125

# Write to custom target

126

custom_target = pyvips.TargetCustom()

127

custom_target.on_write(my_write_handler)

128

image.write_to_target(custom_target, '.webp', Q=80)

129

```

130

131

### Raw Memory Output

132

133

Export raw pixel data for interfacing with other libraries or hardware.

134

135

```python { .api }

136

def write_to_memory(self) -> bytes:

137

"""

138

Write raw pixel data to memory.

139

140

Returns:

141

bytes object containing raw pixel values

142

"""

143

```

144

145

Example usage:

146

147

```python

148

# Get raw pixel data

149

raw_data = image.write_to_memory()

150

151

# Calculate expected size

152

expected_size = image.width * image.height * image.bands

153

if image.format == 'uchar':

154

expected_size *= 1

155

elif image.format == 'ushort':

156

expected_size *= 2

157

elif image.format == 'float':

158

expected_size *= 4

159

160

assert len(raw_data) == expected_size

161

162

# Use with NumPy

163

import numpy as np

164

array = np.frombuffer(raw_data, dtype=np.uint8)

165

array = array.reshape((image.height, image.width, image.bands))

166

```

167

168

### In-Place Writing

169

170

Write image data into another image object for specialized workflows.

171

172

```python { .api }

173

def write(self, other: 'Image') -> None:

174

"""

175

Write this image into another image.

176

177

Parameters:

178

- other: Image, target image to write into

179

180

Returns:

181

None (modifies target image)

182

"""

183

```

184

185

Example usage:

186

187

```python

188

# Create target image

189

target = pyvips.Image.black(800, 600, bands=3)

190

191

# Write processed image into target

192

processed = image.resize(0.5).crop(0, 0, 400, 300)

193

processed.write(target)

194

```

195

196

## Format-Specific Options

197

198

### JPEG Options

199

200

```python

201

# Quality and optimization

202

image.write_to_file('photo.jpg',

203

Q=95, # Quality 1-100

204

optimize=True, # Optimize huffman tables

205

progressive=True, # Progressive encoding

206

strip=True, # Remove metadata

207

interlace=True, # Interlaced

208

trellis_quant=True, # Trellis quantization

209

overshoot_deringing=True, # Overshoot deringing

210

optimize_scans=True, # Optimize scans

211

quant_table=2) # Quantization table

212

```

213

214

### PNG Options

215

216

```python

217

# Compression and format

218

image.write_to_file('image.png',

219

compression=9, # Compression level 0-9

220

interlace=True, # Interlaced

221

palette=True, # Use palette if possible

222

colours=256, # Max colors for palette

223

Q=100, # Quality for 8-bit PNG

224

dither=1.0, # Dithering amount

225

bitdepth=8, # Bit depth

226

filter='all') # PNG filter

227

```

228

229

### WebP Options

230

231

```python

232

# Modern format options

233

image.write_to_file('modern.webp',

234

Q=80, # Quality 0-100

235

lossless=False, # Lossless compression

236

preset='photo', # Preset ('default', 'photo', 'picture', 'drawing', 'icon', 'text')

237

smart_subsample=True, # Smart subsampling

238

near_lossless=False, # Near-lossless

239

alpha_q=100, # Alpha channel quality

240

method=4, # Compression method 0-6

241

target_size=0, # Target size in bytes

242

reduction_effort=4) # Effort level 0-6

243

```

244

245

### TIFF Options

246

247

```python

248

# Professional format options

249

image.write_to_file('document.tiff',

250

compression='lzw', # Compression ('none', 'jpeg', 'deflate', 'packbits', 'lzw', 'webp', 'zstd', 'jp2k')

251

Q=75, # Quality for JPEG compression

252

predictor='horizontal', # Predictor ('none', 'horizontal', 'float')

253

tile=True, # Tiled format

254

tile_width=256, # Tile width

255

tile_height=256, # Tile height

256

pyramid=True, # Pyramid (multi-resolution)

257

miniswhite=False, # Miniswhite photometric

258

bitdepth=8, # Bit depth

259

resunit='in', # Resolution unit

260

xres=300.0, # X resolution

261

yres=300.0) # Y resolution

262

```

263

264

### HEIF/AVIF Options

265

266

```python

267

# Next-generation formats

268

image.write_to_file('image.heic',

269

Q=50, # Quality 1-100

270

compression='hevc', # Compression ('hevc', 'avc', 'jpeg', 'av01')

271

effort=4, # CPU effort 0-9

272

chroma='420', # Chroma subsampling

273

lossless=False) # Lossless compression

274

275

image.write_to_file('image.avif',

276

Q=50, # Quality 1-100

277

compression='av01', # AVIF uses AV1

278

effort=4, # Encoding effort

279

subsample_mode='auto') # Subsampling mode

280

```

281

282

## Multi-page Output

283

284

Handle multi-page formats like TIFF, PDF, and animated formats.

285

286

```python

287

# Create multi-page TIFF

288

pages = [image1, image2, image3]

289

pages[0].write_to_file('multipage.tiff',

290

compression='lzw',

291

strip=True)

292

293

# Append additional pages

294

for page in pages[1:]:

295

page.write_to_file('multipage.tiff',

296

mode='a', # Append mode

297

compression='lzw')

298

299

# Create animated WebP

300

frames = [frame1, frame2, frame3]

301

frames[0].write_to_file('animation.webp',

302

Q=80,

303

delay=[100, 100, 100], # Frame delays in ms

304

loop=0) # Loop count (0 = infinite)

305

```

306

307

## Metadata Preservation

308

309

Control metadata handling during output operations.

310

311

```python

312

# Preserve all metadata

313

image.write_to_file('with_metadata.jpg', strip=False)

314

315

# Remove metadata

316

image.write_to_file('no_metadata.jpg', strip=True)

317

318

# Preserve specific metadata

319

image.write_to_file('selective.jpg',

320

keep='exif,icc') # Keep EXIF and ICC, remove others

321

322

# Set new metadata

323

image_with_meta = image.copy()

324

image_with_meta.set('exif-ifd0-Artist', 'Photographer Name')

325

image_with_meta.set('exif-ifd0-Copyright', '© 2024')

326

image_with_meta.write_to_file('attributed.jpg')

327

```

328

329

## Performance Optimization

330

331

```python

332

# Sequential processing for large images

333

large_image = pyvips.Image.new_from_file('huge.tiff', access='sequential')

334

processed = large_image.thumbnail_image(1000)

335

processed.write_to_file('thumb.jpg', Q=90)

336

337

# Use temporary files for complex pipelines

338

temp = image.thumbnail_image(2000).new_temp_file('.v')

339

result = temp.sharpen().gaussblur(0.5)

340

result.write_to_file('final.jpg')

341

342

# Optimize for specific use cases

343

# Fast web thumbnails

344

thumbnail = image.thumbnail_image(200, crop='attention', linear=False)

345

thumbnail.write_to_buffer('.jpg', Q=80, optimize=True)

346

347

# High-quality print output

348

print_ready = (image

349

.icc_import()

350

.resize(1.0, kernel='lanczos3')

351

.sharpen(radius=0.5)

352

.icc_export(output_profile='printer.icc')

353

.write_to_file('print.tiff', compression='lzw', xres=300, yres=300))

354

```

355

356

## Error Handling

357

358

```python

359

try:

360

image.write_to_file('output.jpg', Q=95)

361

except pyvips.Error as e:

362

print(f"Write failed: {e.message}")

363

print(f"Details: {e.detail}")

364

365

# Check output directory exists

366

import os

367

output_dir = 'output'

368

if not os.path.exists(output_dir):

369

os.makedirs(output_dir)

370

371

image.write_to_file(os.path.join(output_dir, 'result.jpg'))

372

373

# Validate buffer output

374

try:

375

buffer = image.write_to_buffer('.jpg', Q=95)

376

if len(buffer) > 0:

377

print(f"Successfully encoded {len(buffer)} bytes")

378

else:

379

print("Warning: empty buffer")

380

except pyvips.Error as e:

381

print(f"Encoding failed: {e}")

382

```