NAME

Vips::Image - libvips image

SYNOPSIS

use Vips::Image;
use Vips::Const qw(:kernel :format :access);

my $image = Vips::Image->new_from_file('input.jpg', access => VIPS_ACCESS_SEQUENTIAL);
my $small = $image->resize(0.5, kernel => VIPS_KERNEL_LANCZOS3);
my $brighter = ($small * 1.2 + 10)->cast(VIPS_FORMAT_UCHAR);
my $png = $brighter->write_to_buffer('.png', compression => 9);

my ($max, $where) = @{ $image->max(x => 1, y => 1) };
print "max $max at $where->{x},$where->{y}\n";

CALLING OPERATIONS

Any libvips operation is available as a method; Vips::Operations lists them all with their arguments:

$image->resize(0.5);                                  # required arguments
$image->resize(0.5, kernel => VIPS_KERNEL_LINEAR);    # + optional ones
$image->resize(0.5, { kernel => VIPS_KERNEL_LINEAR }); # ... or as a hashref
Vips::Image->black(100, 100, bands => 3);             # class call
$image->linear([1, 2, 3], [0, 0, 0]);                 # array arguments
Vips::Image->bandjoin([$red, $green, $blue]);

The required arguments come first, in the order libvips defines them; for an object call the image itself is the first of them. The rest are optional arguments: name => value pairs or one hashref (_ and - in names are interchangeable). Enum and flags arguments take integer constants from Vips::Const. Where an image is expected a number or an arrayref of numbers may be given: it is turned into a constant image matching the first image argument.

Operations with one output return it directly; with several outputs an arrayref is returned. Optional outputs are requested by passing their name with a true value among the optional arguments; they are returned as a hashref appended to the outputs.

ERRORS

All errors are Vips::Error objects: message, detail (the libvips text) and the file / line of your code. As strings they read like ordinary Perl errors.

LOADING

Constructors are class methods. Options are name => value pairs after the required arguments, as for any operation.

new_from_file($filename, %options)

The loader is chosen from the file contents. Options may also be given in the name: 'input.jpg[shrink=2]'.

new_from_buffer($data, $option_string, %options)

An encoded image (JPEG, PNG, ...) in a Perl string.

new_from_source($source, $option_string, %options)

From a Vips::Source: a file, memory, a descriptor, a Perl handle or callbacks.

new_from_memory($pixels, $width, $height, $bands, $format)

Raw pixels; $format is a VIPS_FORMAT_* constant.

new_from_array(\@matrix, $scale, $offset)

A matrix image (for convolution, morphology etc.) from an arrayref of rows, or of numbers for a single row.

new_from_memory() does not copy the pixels: the image shares the buffer of the Perl string through copy-on-write. Changing or freeing the string later is safe; Perl then copies on its side and the image keeps the old data. new_from_buffer(), Vips::Source->new_from_memory and every blob argument of an operation work the same way, so loading a large file from a string costs no extra memory, whether the string was read at once or built by appending (as an HTTP body is).

SAVING

Output methods are called on the image:

write_to_file($filename, %options)

The format comes from the file name; options may be given in the name too.

write_to_buffer($suffix, %options)

Returns the encoded image as a string; $suffix ('.png', '.jpg[Q=85]') selects the format.

write_to_target($target, $suffix, %options)

Writes to a Vips::Target.

write_to_memory

Raw pixels as a string: row by row, bands interleaved, in the image's format.

to_array

Pixels as an arrayref of rows; a pixel of a multi-band image is an arrayref of band values.

write_to_buffer() returns the encoded image without an extra copy, and write_to_memory() writes the pixels straight into the returned string.

write_to_file() always uses the file saver of the format, like pyvips and the vips command: for example .dz writes a Deep Zoom pyramid (name.dzi and name_files/); pass container => VIPS_FOREIGN_DZ_CONTAINER_ZIP for a single ZIP file.

Loaders and savers are libvips operations, so they can also be called directly (jpegload, pngsave_buffer, thumbnail_source, ...); see Vips::Operations.

OTHER WAYS TO MAKE IMAGES

Images can also be made by generators (black, grey, text, ...), copied to memory with copy_memory(), and made from a constant with new_from_image: an image with the size, format, interpretation, resolution and offset of $image and one band per value:

my $red = $image->new_from_image([255, 0, 0]);

PERFORMANCE

The work happens in libvips; a Perl call costs a few microseconds.

  • Vips::Image->thumbnail($file, $width, ...) decodes a shrunk image directly - for JPEG many times faster than loading and resizing.

  • access => VIPS_ACCESS_SEQUENTIAL when loading streams the image through the pipeline with little memory.

  • Pixels are computed when a result is needed (saving, avg, getpoint): build the pipeline first, then write once.

  • Vips::cache_set_max_mem, Vips::cache_set_max and Vips::concurrency_set tune memory and threads; Vips::block_untrusted_set(1) for untrusted input.

THREADS

Perl callbacks (Vips::Source, Vips::Target) may run in libvips worker threads; they are serialised by one process-wide lock, so a callback must not wait for another callback. Vips objects are not copied into new ithreads: a thread sees an unblessed undef in their place and makes its own objects.

PROPERTIES AND METADATA

width, height, bands, format, interpretation, coding, xres, yres, xoffset, yoffset, filename, hasalpha; get($name), get_typeof($name) (the type name of a field, undef when there is none), get_fields(); describe() gives '309x309 uchar, 3 bands, srgb' for logs.

READING PIXELS

my $pixel = $image->getpoint($x, $y);              # arrayref of band values
my $bytes = $image->fetch($left, $top, $width, $height);

fetch returns the raw pixels of a rectangle as a string: row by row, bands interleaved, in the image's format (see "write_to_memory" for the whole image). It computes just that part of the pipeline through a libvips region, without an operation - the way to serve tiles.

PROGRESS AND CANCELLING

my $tracked = $image->with_progress(sub {
    my %p = @_;      # percent, eta (seconds), run (seconds), tpels, npels
    warn "$p{percent}%\n";
    return 1;        # a defined false value cancels
});
$tracked->resize(0.5)->write_to_file('out.jpg');

with_progress returns a copy of the image; whatever is computed from it reports progress to the callback, from libvips worker threads, while the Perl code waits inside the libvips call. The callback must not call Vips. When it returns a defined false value, or dies, the computation stops and the libvips call fails with a Vips::Error (the exception text is in it).

CHANGING IMAGES

Images are never changed in place: the libvips operation cache and other Perl variables may share them. Metadata is changed, and draw operations may be combined without copying, inside mutate, which works on a private copy and returns it:

my $new = $image->mutate(sub {
    my $m = shift;                       # Vips::MutableImage
    $m->set('my-field', 42);             # type from the value
    $m->set_type('blob', 'icc-profile-data', $bytes);
    $m->remove('exif-data');
    $m->draw_circle(255, 50, 50, 10, fill => 1);   # changes $m
});

Outside mutate, set, set_type and remove croak, and a draw operation (draw_circle, draw_rect, ...) returns a changed copy:

my $marked = $image->draw_rect(255, 0, 0, 10, 10, fill => 1);

OPERATORS

+ - * / % ** & | ^ << >> == != < <= > >=, unary minus and abs work with images, numbers and arrayrefs of numbers (one per band).

CONVENIENCE METHODS

floor ceil rint, sin cos tan asin acos atan sinh cosh tanh asinh acosh atanh log log10 exp exp10, real imag polar rect conj, fliphor flipver, rot90 rot180 rot270, bandand bandor bandeor, bandsplit, median($size), erode($mask), dilate($mask);

$image->bandjoin($alpha, 255);              # images and constants
$cond->ifthenelse($then, 0, blend => 1);    # constants match the other branch
$base->composite($overlay, VIPS_BLEND_MODE_OVER, x => 10, y => 10);
$base->composite([$a, $b], [VIPS_BLEND_MODE_OVER, VIPS_BLEND_MODE_ADD]);