### Install Libvips on Debian/Ubuntu
Source: https://github.com/elixir-image/image/blob/main/README.md
Command to install the libvips development library on Debian or Ubuntu systems using apt.
```bash
# Debian / Ubuntu
apt install libvips-dev
```
--------------------------------
### Install Libvips on Fedora/RHEL
Source: https://github.com/elixir-image/image/blob/main/README.md
Command to install the libvips development library on Fedora or RHEL systems using dnf.
```bash
# Fedora / RHEL
dnf install vips-devel
```
--------------------------------
### Install FFmpeg on Debian/Ubuntu
Source: https://github.com/elixir-image/image/blob/main/README.md
Commands to install FFmpeg development packages on Debian or Ubuntu systems using apt.
```bash
# Debian / Ubuntu
apt install libavcodec-dev libavformat-dev libavutil-dev \
libswscale-dev libavdevice-dev
```
--------------------------------
### Install Platform-Provided libvips
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Instructions for installing libvips on macOS, Debian/Ubuntu, and Fedora/RHEL systems to enable broader format support for Vix.
```bash
# macOS
brew install libvips
# Debian / Ubuntu
apt install libvips-dev
# Fedora / RHEL
dnf install vips-devel
```
--------------------------------
### Install FFmpeg for Xav
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Install FFmpeg and its development libraries required by the Xav package. The installation commands vary by operating system.
```bash
# macOS (Apple Silicon)
brew install pkg-config ffmpeg
```
```bash
# macOS (Intel)
brew install ffmpeg
```
```bash
# Debian / Ubuntu
apt install libavcodec-dev libavformat-dev libavutil-dev \
libswscale-dev libavdevice-dev
```
```bash
# Fedora / RHEL
dnf install pkg-config ffmpeg-devel ffmpeg-libs
```
--------------------------------
### Install libvips with extra codecs
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Install the libvips library using Homebrew with support for HEIF and JPEG XL codecs. Set the VIX_COMPILATION_MODE environment variable to indicate that platform-provided libvips should be used.
```bash
brew install libvips --with-heif --with-jpeg-xl
export VIX_COMPILATION_MODE=PLATFORM_PROVIDED_LIBVIPS
```
--------------------------------
### Install FFmpeg on macOS (Apple Silicon)
Source: https://github.com/elixir-image/image/blob/main/README.md
Command to install FFmpeg development packages on macOS with Apple Silicon using Homebrew.
```bash
# macOS (Apple Silicon)
brew install pkg-config ffmpeg
```
--------------------------------
### Install Libvips on macOS
Source: https://github.com/elixir-image/image/blob/main/README.md
Command to install the libvips development library on macOS using Homebrew.
```bash
# macOS
brew install libvips
```
--------------------------------
### Install FFmpeg on macOS (Intel)
Source: https://github.com/elixir-image/image/blob/main/README.md
Command to install FFmpeg development packages on macOS with Intel processors using Homebrew.
```bash
# macOS (Intel)
brew install ffmpeg
```
--------------------------------
### Install FFmpeg on Fedora/RHEL
Source: https://github.com/elixir-image/image/blob/main/README.md
Commands to install FFmpeg development packages on Fedora or RHEL systems using dnf, including enabling RPM Fusion.
```bash
# Fedora / RHEL
dnf install pkg-config ffmpeg-devel ffmpeg-libs
```
--------------------------------
### Image Configuration
Source: https://github.com/elixir-image/image/blob/main/_autodocs/MANIFEST.txt
Documentation on configuration and setup for the Image library, including libvips environment variables, programmatic configuration, security settings, FFmpeg/Xav setup, optional dependencies, Vix configuration, memory management, and performance tuning.
```APIDOC
## Image Configuration
### Description
Documentation on configuration and setup for the Image library, including libvips environment variables, programmatic configuration, security settings, FFmpeg/Xav setup, optional dependencies, Vix configuration, memory management, and performance tuning.
### Configuration Options
- **libvips Environment Variables**: (Details not specified)
- **Programmatic Configuration**: (Details not specified)
- **Security Settings**: `VIPS_BLOCK_UNTRUSTED` (Details not specified)
- **FFmpeg/Xav Setup**: For video (Details not specified)
- **Optional Dependencies**: Nx, Scholar, Xav, Evision, image_qrcode, etc. (Details not specified)
- **Vix Configuration**: Bundled vs platform libvips (Details not specified)
- **Memory Management**: (Details not specified)
- **Debug Logging**: (Details not specified)
- **Performance Tuning**: (Details not specified)
- **Troubleshooting**: (Details not specified)
```
--------------------------------
### Batch Process Images
Source: https://github.com/elixir-image/image/blob/main/_autodocs/INDEX.md
Provides an example of iterating through multiple image files, creating thumbnails for each, and saving them to a designated directory.
```elixir
files = Path.wildcard("images/*.jpg")
Enum.each(files, fn input ->
{:ok, image} = Image.open(input)
{:ok, thumb} = Image.thumbnail(image, 256)
output = Path.basename(input, ".jpg") <> "_thumb.jpg"
Image.write(thumb, Path.join("thumbs", output), quality: 80)
end)
```
--------------------------------
### Troubleshoot 'libvips not found' Error
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Ensure either the bundled Vix is used by default or that platform libvips is installed and VIX_COMPILATION_MODE=PLATFORM_PROVIDED_LIBVIPS is set.
```bash
# Set at compile time and runtime
export VIX_COMPILATION_MODE=PLATFORM_PROVIDED_LIBVIPS
```
--------------------------------
### Elixir Function Signature Example
Source: https://github.com/elixir-image/image/blob/main/_autodocs/MANIFEST.txt
Demonstrates a typical Elixir function signature with type specifications for parameters and return values.
```elixir
def function_name(param :: Type.t()) ::
{:ok, Result.t()} | {:error, Image.Error.t()}
```
--------------------------------
### Check FFmpeg Development Packages
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Verify that FFmpeg development packages are installed and accessible using pkg-config. This is crucial for Image.Video functionality.
```bash
pkg-config --cflags --libs libavformat
```
--------------------------------
### Elixir Basic Function Call Example
Source: https://github.com/elixir-image/image/blob/main/_autodocs/MANIFEST.txt
A simple example of calling an Elixir function that returns a tuple, typically used for success or error indication.
```elixir
{:ok, result} = Image.function(args)
```
--------------------------------
### Error Handling Example
Source: https://github.com/elixir-image/image/blob/main/_autodocs/types.md
Illustrates how to handle fallible operations using the {:error, %Image.Error{...}} tuple structure. This pattern is common across the library.
```elixir
Example:
```elixir
{:error, %Image.Error{reason: :enoent, path: "/no/file.jpg"}}
```
```
--------------------------------
### Compose Text onto Base Image
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-text.md
Combines a generated text image with a base image. This example demonstrates creating a white base image, generating a header text image, and then composing the header onto the base image at a specific vertical position. The final composed image is then written to a file.
```elixir
{:ok, base} = Image.new(800, 600, color: :white)
{:ok, header} = Image.Text.text("Project Report",
font_size: 48,
font_weight: :bold,
text_fill_color: :navy
)
{:ok, result} = Image.compose([base, {header, x: :center, y: 20}])
:ok = Image.write(result, "report.png")
```
--------------------------------
### Create a new blank image
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Creates a blank image with specified dimensions. Use this when you need to start with an empty image canvas. Returns an {:ok, image} tuple on success or an {:error, error} tuple if dimensions are invalid.
```elixir
Image.new(800, 600)
```
--------------------------------
### Sample Output: :histogram vs :imagequant (Small PNG)
Source: https://github.com/elixir-image/image/blob/main/guides/performance.md
Compares the sample output format for dominant colors extracted using the :histogram and :imagequant methods on a small PNG image.
```text
histogram : [[40, 40, 40], [56, 56, 56], [8, 8, 8], [184, 184, 184], [168, 168, 168]]
imagequant: [{195, 195, 195}, {125, 125, 125}, {91, 91, 91}, {153, 153, 153}, {176, 176, 176}]
```
--------------------------------
### Create and Save a Thumbnail
Source: https://github.com/elixir-image/image/blob/main/guides/thumbnailing.md
Reads an image from binary, creates a thumbnail, and saves it to a file. Ensure the input file path is correct and the output directory is writable.
```elixir
iex> original_raw = File.read!("/path/to_original.jpg"); nil
nil
iex> {:ok, original} = Image.from_binary(original_raw)
{:ok, %Vix.Vips.Image{ref: #Reference<0.4099923103.164495390.164069>}}
iex> {:ok, thumbnail} = Image.thumbnail(original, 200)
{:ok, %Vix.Vips.Image{ref: #Reference<0.4099923103.164495390.164078>}}
iex> Image.write(thumbnail, "/tmp/thumbnail.png")
{:ok, %Vix.Vips.Image{ref: #Reference<0.4099923103.164495390.164078>}}
iex> Image.write(thumbnail, "/path/to_thumbnail.png")
{:ok, %Vix.Vips.Image{ref: #Reference<0.4099923103.164495390.164078>}}
```
--------------------------------
### Create a New Image with Options
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `Image.new/3` to create a new image with specified dimensions and optional parameters like color, bands, format, and interpretation. It returns an {:ok, image} tuple on success or an {:error, error} tuple on failure.
```elixir
{:ok, image} = Image.new(800, 600, color: :red, bands: 4)
```
--------------------------------
### Rebuild Elixir Project
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Clean and recompile your Elixir project after installing or updating dependencies. This ensures that the project uses the newly installed libraries.
```bash
mix clean
mix compile
```
--------------------------------
### Open, Transform, and Write Image
Source: https://github.com/elixir-image/image/blob/main/README.md
Demonstrates opening an image, creating a thumbnail, and writing it to a new file with specified quality.
```elixir
{:ok, image} = Image.open("photo.jpg")
{:ok, thumb} = Image.thumbnail(image, 256)
:ok = Image.write(thumb, "thumb.jpg", quality: 85)
```
--------------------------------
### Open Image from File with Options
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `Image.open/2` to load an image from a file path. Supports options like `:access` for file access patterns and `:fail_on` for error tolerance. Returns an {:ok, image} tuple on success or an {:error, error} tuple on failure.
```elixir
{:ok, image} = Image.open("photo.jpg", access: :sequential)
```
--------------------------------
### Create and Save a New Image
Source: https://github.com/elixir-image/image/blob/main/_autodocs/INDEX.md
Shows the basic workflow for creating a new blank image with specified dimensions and color, and then saving it to a file.
```elixir
{:ok, image} = Image.new(800, 600, color: :white)
{:ok, image} = Image.write(image, "output.png")
```
--------------------------------
### Get Image Dimensions
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-advanced.md
Retrieve the width, height, or number of bands of an image.
```elixir
def width(image :: Vix.Vips.Image.t()) :: pos_integer()
def height(image :: Vix.Vips.Image.t()) :: pos_integer()
def bands(image :: Vix.Vips.Image.t()) :: pos_integer()
```
--------------------------------
### Get Individual Image Dimensions
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `width/1`, `height/1`, and `bands/1` to retrieve specific dimension components of an image.
```elixir
Image.width(image)
Image.height(image)
Image.bands(image)
```
--------------------------------
### Pattern Matching for File and I/O Errors
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Demonstrates how to pattern match on common file and I/O errors like :enoent, :access_error, and {:unsupported_format, format} when opening an image.
```elixir
case Image.open(path) do
{:ok, image} -> process(image)
{:error, %Image.Error{reason: :enoent}} -> Logger.error("File not found: #{path}")
{:error, %Image.Error{reason: :access_error}} -> Logger.error("Permission denied: #{path}")
{:error, %Image.Error{reason: {:unsupported_format, fmt}}} -> Logger.error("Format #{fmt} not supported")
end
```
--------------------------------
### Get Image Colorspace
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Retrieve the current colorspace of an image using the `colorspace/1` function. This returns an atom representing the colorspace.
```elixir
space = Image.colorspace(image)
# => :srgb
```
--------------------------------
### Get Dominant Color of an Image
Source: https://github.com/elixir-image/image/blob/main/README.md
Retrieves the dominant color of an image as RGB values or a palette using different methods.
```elixir
{:ok, [r, g, b]} = Image.dominant_color(image)
{:ok, palette} = Image.dominant_color(image, method: :imagequant, top_n: 8)
# => [{124, 30, 4}, {200, 88, 12}, ...]
```
--------------------------------
### Sample Output: :histogram vs :imagequant (Large JPG)
Source: https://github.com/elixir-image/image/blob/main/guides/performance.md
Compares the sample output format for dominant colors extracted using the :histogram and :imagequant methods on a large JPG image.
```text
histogram : [[8, 24, 40], [8, 40, 56], [24, 104, 168], [40, 104, 168], [40, 120, 184]]
imagequant: [{224, 213, 207}, {187, 154, 121}, {136, 151, 178}, {106, 98, 93}, {63, 122, 180}]
```
--------------------------------
### Constructing Image.Error with Keyword List
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Shows how to create a new `Image.Error` struct using a keyword list for the `reason` and `path` attributes.
```elixir
raise Image.Error, reason: :enoent, path: "/tmp/missing.jpg"
```
--------------------------------
### Load, Transform, and Save Image
Source: https://github.com/elixir-image/image/blob/main/_autodocs/INDEX.md
Illustrates a common workflow for loading an image, resizing it, creating a thumbnail, and saving the thumbnail with a specific quality setting.
```elixir
{:ok, image} = Image.open("input.jpg")
{:ok, resized} = Image.resize(image, width: 640)
{:ok, thumb} = Image.thumbnail(resized, 256)
:ok = Image.write(thumb, "thumb.jpg", quality: 85)
```
--------------------------------
### Get Single Pixel Value
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-advanced.md
Reads the value of a single pixel at specified x and y coordinates. Returns an error if coordinates are out of bounds.
```elixir
{:ok, [r, g, b]} = Image.get_pixel(image, 100, 50)
```
--------------------------------
### Get Image Dimensions and Bands
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
The `shape/1` function returns a tuple containing the image's width, height, and number of color bands.
```elixir
{width, height, bands} = Image.shape(image)
# => {1920, 1080, 3}
```
--------------------------------
### Get Image Shape and Dimensions
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-advanced.md
Retrieves the width, height, and band count of an image. This utility function is useful for analyzing image properties.
```elixir
{w, h, bands} = Image.shape(image)
aspect = if w > h, do: :landscape, else: :portrait
```
--------------------------------
### Create Text Image with Background and Styling
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-text.md
Renders text with a bold font, white color, and a semi-transparent red background with 10 pixels of padding.
```elixir
# Text with background and styling
{:ok, text_img} = Image.Text.text("Warning!",
font_size: 36,
font_weight: :bold,
text_fill_color: :white,
background_fill_color: :red,
background_fill_opacity: 0.8,
padding: 10
)
```
--------------------------------
### Create a New Image (Exception Variant)
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `Image.new!/2` or `Image.new!/3` to create a new image. These functions raise exceptions on error instead of returning error tuples.
```elixir
image = Image.new!(800, 600, color: :white)
```
--------------------------------
### Load Image from Binary Data with Format Detection
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `Image.from_binary/2` to load an image directly from binary data. The function automatically detects the image format. Returns an {:ok, image} tuple on success or an {:error, error} tuple on failure.
```elixir
{:ok, image} = Image.from_binary(jpeg_bytes)
```
--------------------------------
### Get Social Media Image Dimensions
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-advanced.md
Retrieves standard image dimensions for social media platforms and presets. Use this for preprocessing or thumbnail generation.
```elixir
{:ok, {width, height}} = Image.Social.get(:twitter, :profile_image)
{:ok, {width, height}} = Image.Social.get(:instagram, :feed_post)
{:ok, {width, height}} = Image.Social.get(:youtube, :channel_art)
```
--------------------------------
### Open Image from Binary Data
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `Image.open/1` with binary data to load an image. The function attempts to detect the image format automatically. Returns an {:ok, image} tuple on success or an {:error, error} tuple on failure.
```elixir
{:ok, image} = Image.open(binary_jpeg_data)
```
--------------------------------
### Get libvips Concurrency Programmatically
Source: https://github.com/elixir-image/image/blob/main/README.md
Retrieve the current libvips thread pool size using Image.get_concurrency/0. This allows you to inspect the configured concurrency level.
```elixir
Image.get_concurrency()
```
--------------------------------
### Get Pixel Value (Raises Exception)
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-advanced.md
Reads the value of a single pixel at specified x and y coordinates. Raises an exception if coordinates are out of bounds, unlike `get_pixel/3`.
```elixir
pixel() | no_return()
```
--------------------------------
### flood/3, flood/4
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-draw.md
Performs a flood-fill operation starting at specified coordinates. It returns the modified image and the bounds of the filled region, or an error tuple if coordinates are invalid.
```APIDOC
## flood/3, flood/4
### Description
Performs flood-fill (bucket fill) operation starting at coordinates, returns filled region bounds.
### Method
`flood(image, left, top, options \ [])`
### Parameters
#### Path Parameters
- `image` (Vix.Vips.Image.t() | Vix.Vips.MutableImage.t()) - Required - Image to fill
- `left` (non_neg_integer()) - Required - X coordinate of seed point
- `top` (non_neg_integer()) - Required - Y coordinate of seed point
- `options` (keyword list) - Optional - Flood fill options. Defaults to `[]`.
#### Query Parameters
None
#### Request Body
None
### Request Example
```elixir
{:ok, image, %{left: l, top: t, width: w, height: h}} = Image.Draw.flood(image, 50, 50, color: :red, equal_tolerance: 10)
```
### Response
#### Success Response (200)
- `{:ok, image, box}` — image with filled region and bounds
#### Error Response
- `{:error, error}` — on invalid coordinates
### Options
#### `:color`
- Type: `Pixel.t() | atom() | string()`
- Default: `:black`
- Description: Fill color.
#### `:equal_tolerance`
- Type: `0..255`
- Default: `0`
- Description: Color similarity threshold.
```
--------------------------------
### Flood Fill Operation
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-draw.md
Performs a flood-fill operation starting at specified coordinates. Returns the modified image and the bounds of the filled region. Use for bucket-fill effects.
```elixir
{:ok, image, %{left: l, top: t, width: w, height: h}} = Image.Draw.flood(image, 50, 50, color: :red, equal_tolerance: 10)
```
--------------------------------
### Generate Basic Thumbnail
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-transformations.md
Creates a thumbnail that fits within a specified maximum dimension, preserving aspect ratio. This is the fastest thumbnail generation method.
```elixir
{:ok, thumb} = Image.thumbnail(image, 256)
```
--------------------------------
### Set libvips Concurrency Programmatically
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Set the libvips thread pool size at runtime using Image.put_concurrency/1. This is useful for dynamically adjusting concurrency, for example, in multi-tenant systems.
```elixir
# Limit to 4 threads for multi-tenant system
Image.put_concurrency(4)
```
```elixir
# Use all cores
Image.put_concurrency(System.schedulers_online())
```
--------------------------------
### Resize, Crop, and Rotate Image
Source: https://github.com/elixir-image/image/blob/main/README.md
Shows a pipeline for resizing an image to half its scale, cropping it to a specific area, rotating it, and writing the result.
```elixir
image
|> Image.resize!(scale: 0.5)
|> Image.crop!(0, 0, 400, 400)
|> Image.rotate!(15)
|> Image.write!("derived.png")
```
--------------------------------
### Get Current libvips Concurrency Setting
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Read the current libvips concurrency setting using Image.get_concurrency/0. This function returns the number of threads currently configured for the libvips thread pool.
```elixir
current = Image.get_concurrency()
```
--------------------------------
### Constructing Image.Error with String
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Illustrates creating an `Image.Error` by providing a descriptive error message as a string.
```elixir
raise Image.Error, "Unknown encoding error"
```
--------------------------------
### Draw a Line
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-draw.md
Draws a line between two points on an image using Bresenham's algorithm. This is the safe version, returning {:ok, ...} or {:error, ...}. Specify start and end coordinates, and optional color.
```elixir
{:ok, image} = Image.Draw.line(image, 10, 10, 100, 100, color: :yellow)
```
--------------------------------
### Handle Image Open Errors
Source: https://github.com/elixir-image/image/blob/main/_autodocs/INDEX.md
Demonstrates pattern matching on the result of Image.open/1 to handle success and specific error reasons like file not found or invalid options.
```elixir
case Image.open(path) do
{:ok, image} -> process(image)
{:error, %Image.Error{reason: :enoent}} -> not_found()
{:error, %Image.Error{reason: {:invalid_option, opt}}} -> invalid(opt)
end
```
--------------------------------
### new/2
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Creates a blank image with specified dimensions. Returns an {:ok, image} tuple on success or an {:error, error} tuple if dimensions are invalid.
```APIDOC
## new/2
### Description
Creates a blank image with specified dimensions.
### Method
Elixir Function
### Parameters
#### Path Parameters
—
#### Query Parameters
—
#### Request Body
—
### Parameters
- **width** (pos_integer()) - Required - Image width in pixels
- **height** (pos_integer()) - Required - Image height in pixels
### Response
#### Success Response
- **image** (Vix.Vips.Image.t()) - The newly created image
#### Error Response
- **error** (Image.Error.t()) - An error tuple if dimensions are invalid
### Example
```elixir
{:ok, image} = Image.new(800, 600)
```
```
--------------------------------
### Constructing Image.Error with Atom
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Demonstrates creating an `Image.Error` with a simple atom representing the error reason.
```elixir
raise Image.Error, :invalid_color
```
--------------------------------
### Constructing Image.Error with Tuple
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Shows how to construct an `Image.Error` using a tuple, which can include additional details like a file path.
```elixir
raise Image.Error, {:enoent, "/tmp/missing.jpg"}
```
--------------------------------
### Handle Image Open Errors with Pattern Matching
Source: https://github.com/elixir-image/image/blob/main/README.md
Demonstrates robust error handling for image opening operations using pattern matching on Image.Error types.
```elixir
case Image.open(path) do
{:ok, image} -> use_image(image)
{:error, %Image.Error{reason: :enoent}} -> not_found(path)
{:error, %Image.Error{reason: :unsupported_format}} -> wrong_format(path)
{:error, %Image.Error{} = error} -> raise error
end
```
--------------------------------
### Open Image from Stream
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `Image.open/1` with a stream to load an image. This is useful for handling image data from sources like files or network connections without loading the entire data into memory at once. Returns an {:ok, image} tuple on success or an {:error, error} tuple on failure.
```elixir
{:ok, image} = Image.open(File.stream!("image.png"))
```
--------------------------------
### Write Image with Exception Handling
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
The `write!/2` and `write!/3` functions provide a convenient way to write images, raising an exception if an error occurs during the process.
```elixir
Image.write!(image, "output.jpg", quality: 90)
```
--------------------------------
### Open Image (Exception Variant)
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `Image.open!/1` to open an image from a file path. This function raises exceptions on error instead of returning error tuples.
```elixir
image = Image.open!("photo.jpg")
```
--------------------------------
### Image.new/3
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Creates a new image with specified dimensions and optional parameters like color, bands, format, and interpretation. It returns an {:ok, image} tuple on success or an {:error, error} tuple on failure.
```APIDOC
## Image.new/3
### Description
Creates an image with specified dimensions and options.
### Signature
```elixir
def new(width :: pos_integer(), height :: pos_integer(), options :: Options.New.t()) ::
{:ok, Vix.Vips.Image.t()} | {:error, Image.Error.t()}
```
### Parameters
#### Path Parameters
- **width** (pos_integer()) - Required - Image width in pixels
- **height** (pos_integer()) - Required - Image height in pixels
- **options** (keyword list) - Optional - Creation options
### Options
#### New Options
- **:color** (Pixel.t() | atom() | string()) - Optional - Fill color. Defaults to `0` (black).
- **:bands** (integer()) - Optional - Number of bands/channels. Defaults to `3`.
- **:format** (format()) - Optional - Data type and bit depth. Defaults to `{:u, 8}`.
- **:interpretation** (atom()) - Optional - Color space interpretation. Defaults to `:srgb`.
### Returns
- `{:ok, image}` — newly created image
- `{:error, error}` — on invalid options or color
### Example
```elixir
{:ok, image} = Image.new(800, 600, color: :red, bands: 4)
```
```
--------------------------------
### Image.from_binary/2
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Loads an image directly from binary data, automatically detecting the image format. Returns an {:ok, image} tuple or an {:error, error} tuple.
```APIDOC
## Image.from_binary/2
### Description
Loads image from binary data with format detection.
### Signature
```elixir
def from_binary(binary :: binary(), options :: Options.Open.image_open_options() \ []) ::
{:ok, Vix.Vips.Image.t()} | {:error, Image.Error.t()}
```
### Parameters
#### Path Parameters
- **binary** (binary()) - Required - The binary data of the image.
- **options** (keyword list) - Optional - Loading options. Defaults to `[]`.
### Example
```elixir
{:ok, image} = Image.from_binary(jpeg_bytes)
```
```
--------------------------------
### Compose Images with Positioning
Source: https://github.com/elixir-image/image/blob/main/_autodocs/INDEX.md
Shows how to compose multiple images, including overlays with specified coordinates or alignment keywords like :center and :bottom.
```elixir
Image.compose([
base_image,
{overlay, x: 100, y: 50},
{text, x: :center, y: :bottom}
])
```
--------------------------------
### Add Text to an Image
Source: https://github.com/elixir-image/image/blob/main/_autodocs/INDEX.md
Demonstrates how to create a base image, render text onto it, compose them together, and save the final image with text.
```elixir
{:ok, base} = Image.new(800, 600, color: :white)
{:ok, text} = Image.Text.text("Hello World", font_size: 48)
{:ok, result} = Image.compose([base, {text, x: :center, y: :middle}])
:ok = Image.write(result, "with_text.png")
```
--------------------------------
### Image.open!/1, Image.open!/2
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Opens an image from a file path, stream, or binary data, raising exceptions on error.
```APIDOC
## Image.open!/1, Image.open!/2
### Description
Opens an image from file path, stream, or binary data, raising exceptions on error.
### Signature
```elixir
def open!(path_or_stream_or_binary :: image_data(), options :: Options.Open.image_open_options() \ []) ::
Vix.Vips.Image.t() | no_return()
```
### Parameters
#### Path Parameters
- **path_or_stream_or_binary** (image_data()) - Required - Image source
- **options** (keyword list) - Optional - Loading options. Defaults to `[]`.
### Example
```elixir
image = Image.open!("photo.jpg")
```
```
--------------------------------
### Image.new!/2, Image.new!/3
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Creates a new image with specified dimensions and optional parameters. This function raises exceptions on error instead of returning error tuples.
```APIDOC
## Image.new!/2, Image.new!/3
### Description
Creates a new image with specified dimensions and options, raising exceptions on error.
### Signature
```elixir
def new!(width :: pos_integer(), height :: pos_integer()) ::
Vix.Vips.Image.t() | no_return()
def new!(width :: pos_integer(), height :: pos_integer(), options :: Options.New.t()) ::
Vix.Vips.Image.t() | no_return()
```
### Parameters
#### Path Parameters
- **width** (pos_integer()) - Required - Image width in pixels
- **height** (pos_integer()) - Required - Image height in pixels
- **options** (keyword list) - Optional - Creation options
### Example
```elixir
image = Image.new!(800, 600, color: :white)
```
```
--------------------------------
### thumbnail!/3
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-transformations.md
Creates a thumbnail and raises exceptions on error. This is a non-returning function on success.
```APIDOC
## thumbnail!/3
### Description
Raises exceptions on error.
### Method
Image.thumbnail!
### Parameters
#### Path Parameters
- **image** (Vix.Vips.Image.t()) - Required - Image to thumbnail
- **size** (pos_integer()) - Required - Maximum dimension in pixels
- **options** (keyword list) - Optional - Additional options (defaults to `[]`)
#### Query Parameters
- **:crop** (atom()) - Optional - Cropping strategy (defaults to `:none`)
- **:quality** (pos_integer()) - Optional - Output quality (1-100 for JPEG)
### Response
- **Vix.Vips.Image.t() | no_return()** - Returns the thumbnail or no return on success.
### Error Handling
- Raises exceptions on error.
```
--------------------------------
### Image.open/1, Image.open/2
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Opens an image from a file path, stream, or binary data. It supports various options for loading and error handling, returning an {:ok, image} tuple or an {:error, error} tuple.
```APIDOC
## Image.open/1, Image.open/2
### Description
Opens an image from file path, stream, or binary data.
### Signature
```elixir
def open(path_or_stream_or_binary :: image_data(), options :: Options.Open.image_open_options() \ []) ::
{:ok, Vix.Vips.Image.t()} | {:error, Image.Error.t()}
```
### Parameters
#### Path Parameters
- **path_or_stream_or_binary** (image_data()) - Required - Image source
- **options** (keyword list) - Optional - Loading options. Defaults to `[]`.
### Options
#### Universal Options
- **:access** (:random | :sequential) - Optional - File access pattern. Defaults to `:random`.
- **:fail_on** (:none | :truncated | :error) - Optional - Error tolerance level. Defaults to `:none`.
#### JPEG Options
- **:shrink** (1..16) - Optional - Load-time shrink factor. Defaults to `1`.
#### WebP/GIF/TIFF Options
- **:page** (0..100000) - Optional - First page to load. Defaults to `0`.
- **:pages** (-1..100000 | :all) - Optional - Number of pages to load. Defaults to `1`.
- **:scale** (0.0..1024.0) - Optional - (WebP only) Scale on load. Defaults to `1.0`.
### Returns
- `{:ok, image}` — loaded image
- `{:error, error}` — on file not found, invalid format, or read error
### Throws/Rejects
- **Error Type**: `:enoent` - **Condition**: File not found
- **Error Type**: `:unsupported_format` - **Condition**: Unrecognized image format
- **Error Type**: `:access_error` - **Condition**: Permission denied
### Examples
```elixir
# Load from file
{:ok, image} = Image.open("photo.jpg", access: :sequential)
# Load from binary
{:ok, image} = Image.open(binary_jpeg_data)
# Load from stream
{:ok, image} = Image.open(File.stream!("image.png"))
```
```
--------------------------------
### Flip and Flop Images
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `flip/2` to mirror an image horizontally or vertically, and `flop/1` to flip it vertically. Both functions return an {:ok, image} tuple on success or an {:error, Image.Error.t()} on failure.
```elixir
{:ok, flipped} = Image.flip(image, :horizontal)
{:ok, flopped} = Image.flop(image)
```
--------------------------------
### Recommended: Match on :reason for File Not Found
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Use pattern matching on the `:reason` field of the `Image.Error` struct to specifically handle cases like file not found (`:enoent`). This is more robust than string matching.
```elixir
case Image.open(file) do
{:ok, img} -> img
{:error, %Image.Error{reason: :enoent}} -> default_image()
end
```
--------------------------------
### compose!/2
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-transformations.md
Similar to `compose/2`, but raises exceptions on error instead of returning an error tuple.
```APIDOC
## compose!/2
### Description
Raises exceptions on error.
### Signature
def compose!(composition_list :: composition_list(), options :: Options.Compose.t() \ []) ::
Vix.Vips.Image.t() | no_return()
### Parameters
#### `composition_list`
- Type: `[image | {image, options}]`
- Required: yes
- Description: List of images with optional placement
#### `options`
- Type: `keyword list`
- Required: no
- Default: `[]`
- Description: Global composition options
### Composition Element Options
#### `:x`
- Type: `integer() | :left | :center | :right`
- Default: `0`
- Description: Horizontal position
#### `:y`
- Type: `integer() | :top | :middle | :bottom`
- Default: `0`
- Description: Vertical position
#### `:blend_mode`
- Type: `atom()`
- Default: `:over`
- Description: Blending mode
```
--------------------------------
### Compose Images with Exception Handling
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-transformations.md
Use `Image.compose!/2` for image composition when you want exceptions to be raised on errors instead of returning an error tuple.
```elixir
Vix.Vips.Image.t() | no_return()
```
--------------------------------
### thumbnail/3
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Efficiently creates a thumbnail of an image, preserving aspect ratio. Accepts a size and additional options.
```APIDOC
## thumbnail/3
### Description
Efficiently creates a thumbnail preserving aspect ratio.
### Method
```elixir
def thumbnail(image :: Vix.Vips.Image.t(), size :: pos_integer(), options :: Options.Thumbnail.t() \ []) ::
{:ok, Vix.Vips.Image.t()} | {:error, Image.Error.t()}
```
### Parameters
#### Path Parameters
- **image** (Vix.Vips.Image.t()) - Required - Image to thumbnail
- **size** (pos_integer()) - Required - Maximum dimension for the thumbnail
- **options** (keyword list) - Optional - Additional options for thumbnail generation
### Request Example
```elixir
{:ok, thumb} = Image.thumbnail(image, 256)
```
### Response
#### Success Response
- **{:ok, Vix.Vips.Image.t()}** - The generated thumbnail.
#### Error Response
- **{:error, Image.Error.t()}** - An error tuple if thumbnail creation fails.
```
--------------------------------
### Render Text with Pango Markup
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-text.md
Creates an image with text formatted using Pango markup. This allows for inline styling like bold, italic, and color changes within the text string itself. The function returns an {:ok, image} tuple on success.
```elixir
{:ok, image} = Image.Text.text("\nBold Red Text\nNormal text\nItalic Smaller\n")
```
--------------------------------
### thumbnail/2, thumbnail/3
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-transformations.md
Creates a thumbnail fitting within specified dimensions while preserving aspect ratio. Optimized for rapid generation. Returns an OK tuple with the thumbnail or an error tuple.
```APIDOC
## thumbnail/2, thumbnail/3
### Description
Creates a thumbnail fitting within specified max dimension while preserving aspect ratio. Optimized for rapid generation.
### Method
Image.thumbnail
### Parameters
#### Path Parameters
- **image** (Vix.Vips.Image.t()) - Required - Image to thumbnail
- **size** (pos_integer()) - Required - Maximum dimension in pixels
- **options** (keyword list) - Optional - Additional options (defaults to `[]`)
#### Query Parameters
- **:crop** (atom()) - Optional - Cropping strategy (defaults to `:none`)
- **:quality** (pos_integer()) - Optional - Output quality (1-100 for JPEG)
### Response
#### Success Response
- **{:ok, thumbnail}** - thumbnail fitting in size×size box
#### Error Response
- **{:error, error}** - on invalid size
### Request Example
```elixir
# Basic thumbnail (fastest)
{:ok, thumb} = Image.thumbnail(image, 256)
# Thumbnail with center crop to square
{:ok, square_thumb} = Image.thumbnail(image, 256, crop: :center)
# Entropy-based crop (finds interesting region)
{:ok, smart_thumb} = Image.thumbnail(image, 256, crop: :entropy)
```
```
--------------------------------
### Constructing Image.Error from Existing Error
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Demonstrates creating a new `Image.Error` based on an existing `Image.Error` struct.
```elixir
raise Image.Error, %Image.Error{reason: :custom}
```
--------------------------------
### Write Image to File, Stream, or Memory
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `write/2` or `write/3` to save an image to a file path, a file stream, or directly into memory as a binary. Options like `:quality` and `:strip` can be provided for format-specific adjustments.
```elixir
:ok = Image.write(image, "output.jpg", quality: 85)
:ok = Image.write(image, File.stream!("output.png"))
{:ok, binary} = Image.write(image, :memory)
```
--------------------------------
### Add Plug Dependency for HTTP Streaming
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Include the plug package to enable streaming images directly to and from Plug.Conn in web applications.
```elixir
def deps do
[
{:image, "~> 0.64"},
{:plug, "~> 1.14"}
]
end
```
--------------------------------
### Add Kino Dependency for Livebook Integration
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Include the kino package to enable automatic image rendering within Livebook notebooks.
```elixir
def deps do
[
{:image, "~> 0.64"},
{:kino, "~> 0.12"}
]
end
```
--------------------------------
### Create Thumbnail with Maximum Dimension
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Use `thumbnail/2` for efficient thumbnail generation, specifying a maximum dimension while preserving the aspect ratio.
```elixir
{:ok, thumb} = Image.thumbnail(image, 256)
```
--------------------------------
### Set System-Wide Concurrency and Memory Limits
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Configure system-wide memory and concurrency limits for VIPS by setting environment variables. This is useful for multi-tenant or resource-constrained systems.
```bash
# System-wide
export VIPS_CONCURRENCY=2
export VIPS_MAX_MEMORY="256MB"
```
--------------------------------
### Add Image to Dependencies
Source: https://github.com/elixir-image/image/blob/main/README.md
Add the :image library to your project's dependencies in mix.exs.
```elixir
def deps do
[
{:image, ">~ 0.64"}
]
end
```
--------------------------------
### to_colorspace/2
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-core-image.md
Converts an image to a specified colorspace.
```APIDOC
## to_colorspace/2
### Description
Converts an image from its current colorspace to a target colorspace.
### Method
`to_colorspace(image, colorspace)`
### Parameters
- **image** (Vix.Vips.Image.t()) - The input image.
- **colorspace** (atom()) - The target colorspace (e.g., `:srgb`, `:lab`, `:cmyk`).
### Response
- `{:ok, Vix.Vips.Image.t()}` - The image in the target colorspace.
- `{:error, Image.Error.t()}` - An error tuple if the operation fails.
### Supported Spaces
`:srgb`, `:lab`, `:lch`, `:cmyk`, `:scrgb`, `:hsv`, `:xyz`, `:b_w` (black and white).
```
--------------------------------
### Image Pixel and Metadata API
Source: https://github.com/elixir-image/image/blob/main/_autodocs/MANIFEST.txt
This module focuses on pixel and metadata handling, including color conversion, colorspace awareness, EXIF and XMP metadata extraction, and metadata minimization.
```APIDOC
## Image Pixel and Metadata API
### Description
This module focuses on pixel and metadata handling, including color conversion, colorspace awareness, EXIF and XMP metadata extraction, and metadata minimization.
### Modules
- `Image.Pixel`
### Key Operations
- **Color Conversion**: `Image.Pixel.to_pixel/3` (Details not specified)
- **Colorspace Awareness**: (Details not specified)
- **EXIF Metadata Extraction**: (Details not specified)
- **XMP Metadata**: (Details not specified)
- **Metadata Minimization**: (Details not specified)
```
--------------------------------
### Pattern Matching for Option Validation Errors
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Shows how to handle errors related to invalid or missing options, such as :invalid_color or {:invalid_value, {option, value}}, when creating a new image.
```elixir
case Image.new(100, 100, color: :invalid_color) do
{:ok, image} -> image
{:error, %Image.Error{reason: :invalid_color}} ->
Logger.error("Invalid color specified")
{:error, %Image.Error{reason: {:invalid_value, {opt, val}}}} ->
Logger.error("Invalid value for #{opt}: #{val}")
end
```
--------------------------------
### Pattern Matching for Colorspace Errors
Source: https://github.com/elixir-image/image/blob/main/_autodocs/errors.md
Demonstrates how to catch and handle errors related to invalid colorspaces, such as {:invalid_colorspace, space}, when converting an image's colorspace.
```elixir
case Image.to_colorspace(image, :invalid_space) do
{:ok, converted} -> converted
{:error, %Image.Error{reason: {:invalid_colorspace, space}}} ->
Logger.error("Unknown colorspace: #{space}")
end
```
--------------------------------
### Generate Thumbnail with Entropy Crop
Source: https://github.com/elixir-image/image/blob/main/_autodocs/api-transformations.md
Creates a thumbnail using an entropy-based cropping strategy to focus on the most visually interesting region of the image.
```elixir
{:ok, smart_thumb} = Image.thumbnail(image, 256, crop: :entropy)
```
--------------------------------
### Resize Image with Mitchel Interpolation for High Quality
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Employ Mitchel interpolation for image resizing when the highest quality is required, such as in production environments.
```elixir
{:ok, resized} = Image.resize(image, width: 1920, interpolation: :mitchel)
```
--------------------------------
### Configure GLib Debugging
Source: https://github.com/elixir-image/image/blob/main/_autodocs/configuration.md
Configure GLib debugging options by setting the G_DEBUG environment variable. Setting it to 'fatal-criticals' will cause the application to abort on GLib critical messages.
```bash
# Abort on GLib critical messages
export G_DEBUG=fatal-criticals
```
--------------------------------
### Image Text Rendering API
Source: https://github.com/elixir-image/image/blob/main/_autodocs/MANIFEST.txt
The `Image.Text` module handles text rendering using Pango markup, including font selection, styling, background color, opacity, padding, positioning, and transparency.
```APIDOC
## Image Text Rendering API
### Description
The `Image.Text` module handles text rendering using Pango markup, including font selection, styling, background color, opacity, padding, positioning, and transparency.
### Modules
- `Image.Text`
### Key Operations
- **Text Rendering**: With Pango markup (Details not specified)
- **Font Selection and Styling**: (Details not specified)
- **Background Color and Opacity**: (Details not specified)
- **Padding and Positioning**: (Details not specified)
- **Transparency Handling**: (Details not specified)
```