# Image processing (`vips`)

`vips` provides pixel buffers, transforms, filters, colour operations, metadata
readers and image codecs. Its API uses `VipsImage`; it is a Vex package, not a
promise of source compatibility with another image library. Import the facade
from `"vips"`, or a specific component such as `"vips/image"` and
`"vips/transform"` when that is all your program needs.

## Images and ownership

`VipsImage(width, height, channels)` allocates a zero-initialized, tightly packed
8-bit image. `width`, `height`, `channels`, `bitsPerSample` and `bufLen` describe
its storage. A failed allocation or dimension overflow returns a zero-size
sentinel; inspect dimensions before processing. Channels are stored per pixel,
not in separate planes. Supplying four channels does not initialize alpha to
opaque: the initial alpha bytes are also zero.

An owning image frees its allocation when dropped. `freeVipsImage(&image!)`
releases it early and detaches the pointer. Raw buffers and row views borrowed
from an image must stop being used before that release or the owner's drop.
`vipsImageFromBuffer` wraps external storage without taking ownership: the
caller must supply enough live bytes for the declared dimensions and channels.
Do not duplicate the ownership fields to create a second owner.

## Transform a small image

This complete example creates two RGBA pixels, flips them, and checks their
values. It does not need an image file or codec provider.

```vex [image-flip.vx]
import { VipsImage } from "vips/image";
import { flipHorizontal } from "vips/transform";

fn main() {
    let! image = VipsImage(2, 1, 4);
    if image.width != 2 || image.bufLen != 8 { $panic("allocation failed"); }
    image.pixel16Set(0, 0, 0, 255);
    image.pixel16Set(0, 0, 3, 255);
    image.pixel16Set(1, 0, 2, 255);
    image.pixel16Set(1, 0, 3, 255);

    flipHorizontal(&image!);
    if image.pixel16(0, 0, 2) != 255 { $panic("blue pixel missing"); }
    if image.pixel16(1, 0, 0) != 255 { $panic("red pixel missing"); }
    $println("image flip: PASS");
}
```

The `pixel16` accessors also accept an 8-bit image: reads widen to `u16`, while
writes narrow to a byte. Out-of-range reads return zero and writes do nothing.
Do not use those behaviours as an image-layout validator.

For resampling, allocate a destination with the desired dimensions and matching
channel layout. This function fragment returns an independent owned image:

```vex
import { VipsImage } from "vips/image";
import { resizeBilinear } from "vips/transform";

fn thumbnail(source: &VipsImage): VipsImage {
    let! result = VipsImage(160, 90, source.channels);
    if result.width == 0 { return result; }
    resizeBilinear(source, &result!);
    return result;
}
```

Use an 8-bit source for this byte-based transform. Select output dimensions to
preserve aspect ratio when stretching is not intended. `rotate90` requires a
destination whose width and height are swapped. Caller-supplied destinations
must be correctly sized and must not overlap a source read by the operation.

## Read and write images

| API | Behaviour |
| --- | --- |
| `loadImage(path)` | Reads the file and uses the universal native decoder; returns an image sentinel on failure |
| `decodeImage(buffer, length)` | Detects BMP, QOI and P5/P6 Netpbm for Vex decoding; other formats use the native decoder |
| `decodeRaw(buffer, width, height, channels)` | Wraps raw packed pixels without copying or taking ownership; the caller supplies live storage and dimensions |
| `saveImage(&image, path)` | Writes **PPM**, regardless of the filename extension |
| `saveJpeg(&image, path, quality)` | Native JPEG output; quality 1–100, values below 1 select 80 |
| `savePng(&image, path)` | Native PNG output |
| `saveWebp(&image, path, quality)` | Native WebP output; the codec provider determines encoding support |

The save functions return an integer status, with zero indicating success.
Check it before reporting that a file was written. `decodeImage`'s length
describes readable input bytes; `RawBuf` itself carries no allocation extent.

JPEG/PNG and additional universal-decoder formats depend on native codec
providers declared by the package. Provision the selected providers for the
target system; a format name in the dispatch path is not an embedded codec.
Use explicit decode/encode functions when the application needs a fixed format
policy. [FFI](../guide/ffi.md) explains native-library integration.

## Processing operations

| Area | Entry points |
| --- | --- |
| Geometry | `flipHorizontal`, `flipVertical`, `rotate90`, `rotate`, bilinear/bicubic/Lanczos resize |
| Colour | `gammaCorrection`, `compositeOver`, grayscale/brightness helpers, RGB/XYZ/Lab conversion |
| Filtering | `applyBoxBlur`, `applyGaussianBlur`, `applySharpen`, `applySobel`, `conv2d` |
| Morphology | `applyDilate`, `applyErode`, open/close, gradient, top-hat/black-hat, Canny |
| Arithmetic | `addImage`, `subImage`, `linearBlend`, `absDiff` with explicit destinations |
| Distribution | `histogramFind`, `histogramEqualize`, `medianFilter`, `chanStats` |
| Drawing | `drawLine`, `drawRect`, `drawCircle` |
| Channels | `bandExtract`, `bandMerge` |
| Frequency domain | `fft1d`, `fft2dForward`, `fft2dInverse` |
| Metadata | `parseExifOrientation`, `stripMetadata`, `parseIccProfile` |

Each operation has a layout contract. The ordinary transforms and many filters
read byte samples; a `VipsImage16` is not automatically accepted by every
8-bit operation. Use the 16-bit accessors for 16-bit data and convert deliberately
before byte-oriented processing. Raw outputs such as `snapshotPixels` are
caller-owned allocations; they are not automatically attached to an image.

## Rows, views and media integration

`scanline(y)` and `scanlines()` expose borrowed rows; `writeScanline` writes a
row into a destination. Keep the image alive while using a row and avoid
retaining a mutable alias during another operation on the same pixels.
`processRows` and `streamProcess` accept row callbacks. `openJpegStream` provides
a native JPEG scanline decoder whose `close()` releases its provider state.
These APIs distinguish row-wise processing from loading an entire encoded file.

`cropVipsImage` creates a non-owning view. For downstream tightly packed
8-bit operations, use full-width row ranges or copy the selected pixels into a new
owning image with the required layout. The image descriptor does not carry an
independent row-stride field.

The [media package](media.md) bridges 8-bit, three-channel RGB images with
`vipsToMediaTensor` and `mediaTensorToVips`. Both copy into independent owning
storage; they do not transfer the original pointer or convert RGBA/YUV layouts.
