# Vips — Perl binding for libvips [libvips](https://www.libvips.org/) is a fast image processing library with low memory needs: it streams images through a pipeline of operations instead of decoding them whole. This distribution makes all of its 300+ operations available from Perl, in the same style as pyvips and ruby-vips. Only plain Perl values cross the API — numbers, strings, array and hash references, code references — plus the classes `Vips::Image`, `Vips::Source` and `Vips::Target`. ## Installation You need libvips 8.14 or later with its development files, a C compiler and Perl 5.20 or later. ```sh # Debian / Ubuntu apt install libvips-dev build-essential pkg-config # macOS brew install vips pkg-config perl Makefile.PL make make test make install ``` ## Quick start ```perl use Vips::Image; use Vips::Const qw(:kernel :format); my $image = Vips::Image->new_from_file('photo.jpg'); my $small = $image->resize(0.5, kernel => VIPS_KERNEL_LANCZOS3); $small->write_to_file('small.png'); printf "%dx%d, %d bands\n", $image->width, $image->height, $image->bands; ``` The examples below assume `use Vips::Image;` and `use Vips::Const qw(:all);`. ## Loading and saving Constructors (`new_from_*`) are class methods of `Vips::Image`; output methods (`write_to_*`, `to_array`) are called on the image. ```perl # files: the format comes from the name; options as name => value pairs my $image = Vips::Image->new_from_file('photo.jpg'); my $fast = Vips::Image->new_from_file('photo.jpg', access => VIPS_ACCESS_SEQUENTIAL); my $half = Vips::Image->new_from_file('photo.jpg[shrink=2]'); # options in the name $image->write_to_file('out.jpg', Q => 90); $image->write_to_file('out.png[compression=9]'); # memory: encoded bytes in a Perl string my $png = $image->write_to_buffer('.png'); my $copy = Vips::Image->new_from_buffer($png, ''); # raw pixels (not copied: the image shares the string's buffer) my $pixels = $image->write_to_memory; my $raw = Vips::Image->new_from_memory($pixels, $image->width, $image->height, $image->bands, $image->format); ``` ## Properties and metadata ```perl my $image = Vips::Image->new_from_file('photo.jpg'); my ($w, $h, $bands) = ($image->width, $image->height, $image->bands); print "sRGB\n" if $image->interpretation == VIPS_INTERPRETATION_SRGB; print "8 bit\n" if $image->format == VIPS_FORMAT_UCHAR; print "alpha\n" if $image->hasalpha; my $dpi = $image->xres * 25.4; my @fields = $image->get_fields; # all metadata names my $width = $image->get('width'); # any field by name my $type = $image->get_typeof('exif-data'); # type name, undef if absent print $image->describe, "\n"; # "309x309 uchar, 3 bands, srgb" my $pixel = $image->getpoint(10, 20); # [r, g, b] my $tile = $image->fetch(0, 0, 64, 64); # raw pixels of a rectangle, one string ``` ## Calling operations Every libvips operation is a method. Required arguments come first, in the order libvips defines them; optional arguments follow as name => value pairs or as one hash reference. `perldoc Vips::Operations` lists every operation with its arguments. ### On one image ```perl my $image = Vips::Image->new_from_file('photo.jpg'); my $resized = $image->resize(0.25); my $cropped = $image->extract_area(10, 20, 100, 50); # left, top, width, height my $flipped = $image->flip(VIPS_DIRECTION_HORIZONTAL); # enums: Vips::Const integers my $rotated = $image->rot90; # convenience method my $grey = $image->colourspace(VIPS_INTERPRETATION_B_W); my $avg = $image->avg; # a number ``` ### With optional arguments ```perl my $image = Vips::Image->new_from_file('photo.jpg'); my $a = $image->resize(0.5, kernel => VIPS_KERNEL_LINEAR, vscale => 0.25); my $b = $image->resize(0.5, { kernel => VIPS_KERNEL_LINEAR, vscale => 0.25 }); my $c = $image->gaussblur(2, precision => VIPS_PRECISION_INTEGER); ``` ### Creating images (class methods) ```perl my $black = Vips::Image->black(100, 50); # all required: width, height my $rgb = Vips::Image->black(100, 50, bands => 3); my $ramp = Vips::Image->xyz(256, 256); # pixel value = coordinates my $thumb = Vips::Image->thumbnail('photo.jpg', 128); # load + shrink in one go my $kernel = Vips::Image->new_from_array([[1, 2, 1], [2, 4, 2], [1, 2, 1]], 16); ``` ### With several images ```perl my $image = Vips::Image->new_from_file('photo.jpg'); my $other = $image->flip(VIPS_DIRECTION_VERTICAL); my $sum = $image->add($other); # second image as an argument my @bands = @{ $image->bandsplit }; # arrayref of one-band images my $rgb = Vips::Image->bandjoin([@bands]); # array of images: an arrayref my $rgba = $image->bandjoin(255); # add a constant band my $mask = $image->extract_band(0) > 128; # 255 / 0 my $mixed = $mask->ifthenelse($image, $other); # per-pixel choice my $blend = $mask->ifthenelse([255, 0, 0], $image, blend => 1); # constants work too my $base = $rgba->copy(interpretation => VIPS_INTERPRETATION_SRGB); my $overlay = $base->new_from_image([0, 0, 255, 128])->extract_area(0, 0, 50, 50); my $out = $base->composite($overlay, VIPS_BLEND_MODE_OVER, x => 20, y => 20); ``` Where an image argument is expected, a number or an array reference of numbers (one per band) is accepted and turned into a constant image. ### Array arguments ```perl my $image = Vips::Image->new_from_file('photo.jpg'); my $scaled = $image->linear([1.2, 1.0, 0.8], [10, 0, -10]); # per band a * x + b my $same = $image->linear(1.2, 10); # a scalar is a 1-element array my $sharp = $image->conv(Vips::Image->new_from_array([[-1, -1, -1], [-1, 16, -1], [-1, -1, -1]], 8)); ``` ### Several results and optional results ```perl my $image = Vips::Image->new_from_file('photo.jpg'); # one result is returned as is my $max = $image->max; # optional results: ask for them by name; a hashref is appended my ($value, $where) = @{ $image->max(x => 1, y => 1) }; print "maximum $value at ($where->{x}, $where->{y})\n"; # array results are arrayrefs my $pixel = $image->getpoint(10, 20); # [r, g, b] ``` ## Operators Arithmetic, bitwise and comparison operators work on images, numbers and array references (one value per band): ```perl my $image = Vips::Image->new_from_file('photo.jpg'); my $brighter = $image * 1.2 + 10; my $inverted = 255 - $image; my $tinted = $image * [1.0, 0.9, 0.8]; my $average = ($image + $image->flip(VIPS_DIRECTION_HORIZONTAL)) / 2; my $mask = $image > 128; # per band: 255 where true, 0 else my $both = ($image > 64) & ($image < 192); my $abs = abs($image - 128); my $back = $brighter->cast(VIPS_FORMAT_UCHAR); # back to 8 bit ``` ## Changing images Images are never changed in place: the libvips operation cache and other Perl variables may share them. Change metadata and draw inside `mutate`, which works on a private copy and returns it: ```perl my $image = Vips::Image->new_from_file('photo.jpg'); my $marked = $image->mutate(sub { my $m = shift; # a Vips::MutableImage $m->set('my-comment', 'checked'); # metadata $m->remove('exif-data'); $m->draw_rect([255, 0, 0], 10, 10, 50, 50, fill => 1); # draws into $m $m->draw_circle([0, 255, 0], 100, 100, 30); }); # outside mutate a draw operation returns a changed copy my $boxed = $image->draw_rect([255, 255, 0], 0, 0, 20, 20, fill => 1); ``` ## Errors Every error is a `Vips::Error` object. As a string it reads like a normal Perl error, pointing at your code: ```perl my $image = Vips::Image->new_from_file('photo.jpg'); eval { $image->extract_area(0, 0, 100_000, 10) }; if (my $error = $@) { print "message: ", $error->message, "\n"; # Can't build operation extract_area print "libvips: ", $error->detail, "\n"; # extract_area: bad extract area print "at ", $error->file, " line ", $error->line, "\n"; } ``` ## Streaming: sources and targets ```perl # any Perl filehandle, including in-memory ones open my $in, '<', 'photo.jpg' or die $!; my $image = Vips::Image->new_from_source(Vips::Source->new_from_handle($in), ''); my $png = ''; open my $out, '>', \$png or die $!; $image->write_to_target(Vips::Target->new_to_handle($out), '.png'); close $out; # or callbacks my $data = do { local (@ARGV, $/) = 'photo.jpg'; <> }; my $pos = 0; my $source = Vips::Source->new_from_callbacks(read => sub { my ($length) = @_; my $chunk = substr($data, $pos, $length); $pos += length $chunk; return $chunk; # '' at the end }); my $from_callbacks = Vips::Image->new_from_source($source, ''); ``` Callbacks may run in libvips worker threads while your code waits inside a libvips call: keep them short and don't call Vips from inside them. ## Performance tips ```perl # Thumbnails: thumbnail() decodes a shrunk image directly (for JPEG many # times faster than loading the whole image and resizing it). my $thumb = Vips::Image->thumbnail('photo.jpg', 300, height => 300, crop => VIPS_INTERESTING_ATTENTION); # Streaming: with sequential access libvips reads, processes and writes in # one pass, holding only a few lines of pixels in memory. my $image = Vips::Image->new_from_file('photo.jpg', access => VIPS_ACCESS_SEQUENTIAL); $image->resize(0.5)->write_to_file('half.jpg'); # Resources: the operation cache and the number of worker threads. Vips::cache_set_max_mem(100 * 1024 * 1024); # bytes Vips::cache_set_max(500); # operations Vips::concurrency_set(4); # threads per image # Untrusted input (uploads): disable loaders not designed for hostile files. Vips::block_untrusted_set(1); ``` - Pixels are computed when a result is needed (saving, `avg`, `getpoint`…): build the whole pipeline first, then write once. - `write_to_memory` / `new_from_memory` move raw pixels without encoding; `new_from_memory` doesn't even copy them. - Each Perl call to libvips costs a few microseconds; the work is in libvips, so prefer one operation on a whole image over many on small pieces. ## Progress and cancelling ```perl my $image = Vips::Image->new_from_file('photo.jpg'); my $tracked = $image->with_progress(sub { my %p = @_; # percent, eta, run (seconds), tpels, npels print "$p{percent}%\n"; return $p{percent} < 50; # a defined false value cancels the work }); # everything computed from $tracked reports progress; a cancelled # computation fails with a Vips::Error my $ok = eval { $tracked->resize(0.5)->write_to_file('half.jpg'); 1 }; print "cancelled\n" unless $ok; ``` The callback runs in libvips worker threads while your code waits inside the libvips call: keep it short and do not call Vips from it. ## Threads and fork Vips objects belong to the Perl thread that made them; a new ithread sees undef in their place and makes its own. libvips starts worker threads when it first computes something: in a forking server, load and process images in the child processes. ## Documentation - `perldoc Vips::Image` — the image class: loading and saving, operators, metadata - `perldoc Vips::Operations` — every libvips operation with its arguments - `perldoc Vips::Const` — constants for enum and flags arguments - `perldoc Vips::Source`, `perldoc Vips::Target` — streaming - `perldoc Vips::Error` — errors - `perldoc Vips` — cache, threads, security settings - [libvips documentation](https://www.libvips.org/API/current/) ## License MIT License — see `LICENSE`.