Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Leonard edited this page Dec 16, 2013 · 12 revisions

Documentation and examples for libvips, and the Python binding in particular is pretty sparse/arcane. Hopefully this will help.

The Python lib is SWIG'd from the vips7 C++ API. The vips8 C API is very close, it might be helpful. The Python page on the main vips wiki has some more links and notes.

Loading libvips

Including the library:

from vipsCC import *

You can control concurrency (threads) via an environment variable. To set this easily in Python:

import os
os.environ['IM_CONCURRENCY'] = '1'

Basic File I/O

Load an image:

im = VImage.VImage('example.jpg')

Load a jpeg w/ libjpeg's built in (very fast) scaling. This makes the image 2x smaller:

im = VImage.VImage('example.jpg:2')

Sequential mode increases CPU but greatly decreases memory usage:

im = VImage.VImage('example.jpg:,,seq')

You can use it in combination with libjpeg scaling:

im = VImage.VImage('example.jpg:2,,seq')

To set the image quality of a JPEG, append :[0-100] to the filename.

im.write('example.jpg:95')

Image Info

Get image dimensions:

x = im.Xsize()
y = im.Ysize()

Cropping

Extracting/cropping a 500x400px image area 200px to the left and 100px down:

x_offset = 200
y_offset = 100
width = 500
height = 400
tile = im.extract_area(x_offset, y_offset, width, height)

Resizing

Basic image scaling:

target_width = 1024
target_height = 768
scaleX = float(target_width)/im.Xsize()
scaleY = float(target_height)/im.Ysize()
im = im.affine(scaleX, 0, 0, scaleY, 0, 0,
               0, 0, target_width, target_height)

Image Rotation

Rotate -90 degrees (CCW):

height = im.Xsize()
width = im.Ysize()
im = im.affine(0, 1, -1, 0, 0, 0,
               0, -width, height, width)

Rotate 90 degrees (CW):

height = im.Xsize()
width = im.Ysize()
im = im.affine(0, -1, 1, 0, 0, 0,
               -height, 0, height, width)

Rotate 180 degrees (Upside Down):

height = im.Xsize()
width = im.Ysize()
im = im.affine(-1, 0, 0, -1, 0, 0,
               -width, -height, width, height)

More Resources

See also:

There's a lot more examples for the Ruby libs, they may be useful:

Clone this wiki locally