Python binding for the libvips image processing library with high-performance streaming architecture
—
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.
Save images to filesystem with automatic format detection and comprehensive format options.
def write_to_file(self, vips_filename: str, **kwargs) -> None:
"""
Write image to file.
Parameters:
- vips_filename: str, output file path (format auto-detected from extension)
- Q: int, quality (1-100 for JPEG, WebP)
- compression: str/int, compression type/level
- strip: bool, remove metadata
- optimize: bool, optimize file size
- progressive: bool, progressive encoding
- Format-specific options vary by file type
Returns:
None (writes to disk)
"""Example usage:
# Basic file save (format from extension)
image.write_to_file('output.jpg')
image.write_to_file('output.png')
image.write_to_file('output.webp')
# JPEG with quality and optimization
image.write_to_file('photo.jpg', Q=95, optimize=True, progressive=True)
# PNG with compression
image.write_to_file('image.png', compression=9, strip=True)
# TIFF with specific compression
image.write_to_file('data.tiff', compression='lzw', tile=True)
# WebP with quality and lossless option
image.write_to_file('modern.webp', Q=80, lossless=False, strip=True)Write images to memory buffers for network transmission, further processing, or embedding.
def write_to_buffer(self, format_string: str, **kwargs) -> bytes:
"""
Write image to memory buffer.
Parameters:
- format_string: str, output format ('.jpg', '.png', '.webp', etc.)
- Same format-specific options as write_to_file
Returns:
bytes object containing encoded image data
"""Example usage:
# Basic buffer output
jpeg_data = image.write_to_buffer('.jpg')
png_data = image.write_to_buffer('.png')
# High-quality JPEG
jpeg_data = image.write_to_buffer('.jpg', Q=95, optimize=True)
# Compressed PNG
png_data = image.write_to_buffer('.png', compression=9)
# WebP with options
webp_data = image.write_to_buffer('.webp', Q=80, lossless=False)
# Use buffer data
import requests
files = {'image': ('photo.jpg', jpeg_data, 'image/jpeg')}
response = requests.post('https://api.example.com/upload', files=files)
# Save buffer to file
with open('output.jpg', 'wb') as f:
f.write(jpeg_data)Write images to Target objects for advanced I/O scenarios and streaming operations.
def write_to_target(self, target: 'Target', format_string: str, **kwargs) -> None:
"""
Write image to Target object.
Parameters:
- target: Target object for output
- format_string: str, output format
- Same format-specific options as write_to_file
Returns:
None (writes to target)
"""Example usage:
# Write to file target
target = pyvips.Target.new_to_file('output.jpg')
image.write_to_target(target, '.jpg', Q=90)
# Write to memory target
target = pyvips.Target.new_to_memory()
image.write_to_target(target, '.png', compression=6)
buffer_data = target.get()
# Write to custom target
custom_target = pyvips.TargetCustom()
custom_target.on_write(my_write_handler)
image.write_to_target(custom_target, '.webp', Q=80)Export raw pixel data for interfacing with other libraries or hardware.
def write_to_memory(self) -> bytes:
"""
Write raw pixel data to memory.
Returns:
bytes object containing raw pixel values
"""Example usage:
# Get raw pixel data
raw_data = image.write_to_memory()
# Calculate expected size
expected_size = image.width * image.height * image.bands
if image.format == 'uchar':
expected_size *= 1
elif image.format == 'ushort':
expected_size *= 2
elif image.format == 'float':
expected_size *= 4
assert len(raw_data) == expected_size
# Use with NumPy
import numpy as np
array = np.frombuffer(raw_data, dtype=np.uint8)
array = array.reshape((image.height, image.width, image.bands))Write image data into another image object for specialized workflows.
def write(self, other: 'Image') -> None:
"""
Write this image into another image.
Parameters:
- other: Image, target image to write into
Returns:
None (modifies target image)
"""Example usage:
# Create target image
target = pyvips.Image.black(800, 600, bands=3)
# Write processed image into target
processed = image.resize(0.5).crop(0, 0, 400, 300)
processed.write(target)# Quality and optimization
image.write_to_file('photo.jpg',
Q=95, # Quality 1-100
optimize=True, # Optimize huffman tables
progressive=True, # Progressive encoding
strip=True, # Remove metadata
interlace=True, # Interlaced
trellis_quant=True, # Trellis quantization
overshoot_deringing=True, # Overshoot deringing
optimize_scans=True, # Optimize scans
quant_table=2) # Quantization table# Compression and format
image.write_to_file('image.png',
compression=9, # Compression level 0-9
interlace=True, # Interlaced
palette=True, # Use palette if possible
colours=256, # Max colors for palette
Q=100, # Quality for 8-bit PNG
dither=1.0, # Dithering amount
bitdepth=8, # Bit depth
filter='all') # PNG filter# Modern format options
image.write_to_file('modern.webp',
Q=80, # Quality 0-100
lossless=False, # Lossless compression
preset='photo', # Preset ('default', 'photo', 'picture', 'drawing', 'icon', 'text')
smart_subsample=True, # Smart subsampling
near_lossless=False, # Near-lossless
alpha_q=100, # Alpha channel quality
method=4, # Compression method 0-6
target_size=0, # Target size in bytes
reduction_effort=4) # Effort level 0-6# Professional format options
image.write_to_file('document.tiff',
compression='lzw', # Compression ('none', 'jpeg', 'deflate', 'packbits', 'lzw', 'webp', 'zstd', 'jp2k')
Q=75, # Quality for JPEG compression
predictor='horizontal', # Predictor ('none', 'horizontal', 'float')
tile=True, # Tiled format
tile_width=256, # Tile width
tile_height=256, # Tile height
pyramid=True, # Pyramid (multi-resolution)
miniswhite=False, # Miniswhite photometric
bitdepth=8, # Bit depth
resunit='in', # Resolution unit
xres=300.0, # X resolution
yres=300.0) # Y resolution# Next-generation formats
image.write_to_file('image.heic',
Q=50, # Quality 1-100
compression='hevc', # Compression ('hevc', 'avc', 'jpeg', 'av01')
effort=4, # CPU effort 0-9
chroma='420', # Chroma subsampling
lossless=False) # Lossless compression
image.write_to_file('image.avif',
Q=50, # Quality 1-100
compression='av01', # AVIF uses AV1
effort=4, # Encoding effort
subsample_mode='auto') # Subsampling modeHandle multi-page formats like TIFF, PDF, and animated formats.
# Create multi-page TIFF
pages = [image1, image2, image3]
pages[0].write_to_file('multipage.tiff',
compression='lzw',
strip=True)
# Append additional pages
for page in pages[1:]:
page.write_to_file('multipage.tiff',
mode='a', # Append mode
compression='lzw')
# Create animated WebP
frames = [frame1, frame2, frame3]
frames[0].write_to_file('animation.webp',
Q=80,
delay=[100, 100, 100], # Frame delays in ms
loop=0) # Loop count (0 = infinite)Control metadata handling during output operations.
# Preserve all metadata
image.write_to_file('with_metadata.jpg', strip=False)
# Remove metadata
image.write_to_file('no_metadata.jpg', strip=True)
# Preserve specific metadata
image.write_to_file('selective.jpg',
keep='exif,icc') # Keep EXIF and ICC, remove others
# Set new metadata
image_with_meta = image.copy()
image_with_meta.set('exif-ifd0-Artist', 'Photographer Name')
image_with_meta.set('exif-ifd0-Copyright', '© 2024')
image_with_meta.write_to_file('attributed.jpg')# Sequential processing for large images
large_image = pyvips.Image.new_from_file('huge.tiff', access='sequential')
processed = large_image.thumbnail_image(1000)
processed.write_to_file('thumb.jpg', Q=90)
# Use temporary files for complex pipelines
temp = image.thumbnail_image(2000).new_temp_file('.v')
result = temp.sharpen().gaussblur(0.5)
result.write_to_file('final.jpg')
# Optimize for specific use cases
# Fast web thumbnails
thumbnail = image.thumbnail_image(200, crop='attention', linear=False)
thumbnail.write_to_buffer('.jpg', Q=80, optimize=True)
# High-quality print output
print_ready = (image
.icc_import()
.resize(1.0, kernel='lanczos3')
.sharpen(radius=0.5)
.icc_export(output_profile='printer.icc')
.write_to_file('print.tiff', compression='lzw', xres=300, yres=300))try:
image.write_to_file('output.jpg', Q=95)
except pyvips.Error as e:
print(f"Write failed: {e.message}")
print(f"Details: {e.detail}")
# Check output directory exists
import os
output_dir = 'output'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
image.write_to_file(os.path.join(output_dir, 'result.jpg'))
# Validate buffer output
try:
buffer = image.write_to_buffer('.jpg', Q=95)
if len(buffer) > 0:
print(f"Successfully encoded {len(buffer)} bytes")
else:
print("Warning: empty buffer")
except pyvips.Error as e:
print(f"Encoding failed: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-pyvips