### Install Vix and Dependencies Source: https://hexdocs.pm/vix/introduction Demonstrates how to install the Vix library along with Kino for interactive examples and Req for fetching sample images using Mix.install. It also shows how to check the Vix and libvips version. ```Elixir Mix.install([ {:vix, "~> 0.5"}, {:kino, "~> 0.7"}, # For interactive examples {:req, "~> 0.4"} # For fetching sample images ]) IO.puts("Using libvips version: " <> Vix.Vips.version()) ``` -------------------------------- ### Fetch Sample Image for Examples Source: https://hexdocs.pm/vix/introduction Imports the ImageHelper module and uses it to fetch a sample image of 800x600 pixels for use in subsequent examples. ```Elixir import ImageHelper # For our examples, let's use a sample image. image = get_sample_image(800, 600) ``` -------------------------------- ### Install Vix and Create Thumbnail Source: https://hexdocs.pm/vix/readme This snippet demonstrates how to install the Vix library using Mix.install and then create a thumbnail of an image, optimizing it for web with specific quality and strip settings. ```Elixir Mix.install([{:vix,"~> 0.23"}]) alias Vix.Vips.{Image,Operation} # Create a thumbnail and optimize for web {:ok, thumb} = Operation.thumbnail("profile.jpg", 300) :ok = Image.write_to_file(thumb, "thumbnail.jpg", Q: 90, strip: true, interlace: true) ``` -------------------------------- ### Install Vix Dependency Source: https://hexdocs.pm/vix/readme Adds Vix to your project's dependencies. Vix includes pre-built binaries for MacOS and Linux, simplifying the installation process. ```Elixir defdepsdo([:vix, "~> x.x.x"]) end ``` -------------------------------- ### Install Vix and Kino Dependencies Source: https://hexdocs.pm/vix/picture-language This snippet shows how to install the necessary Elixir dependencies, Vix and Kino, using Mix.install. These are required for image processing and inline display. ```elixir Mix.install([ {:kino, "~> 0.3.0"}, {:vix, "~> 0.5"} ]) ``` -------------------------------- ### Install Vix and Kino Libraries Source: https://hexdocs.pm/vix/rainbow This snippet shows how to install the necessary Vix and Kino libraries using Mix, the Elixir build tool. These libraries are essential for utilizing the image processing capabilities provided by Vix and the interactive features of Kino. ```elixir Mix.install([{:vix,"~> 0.22.0"},{:kino,"~> 0.10.0"}]) ``` -------------------------------- ### Generate Color Gradient with buildlut and User Input Source: https://hexdocs.pm/vix/rainbow This snippet shows how to create a color gradient based on user-selected start and end colors. It utilizes `Kino.Input.color/2` to get color inputs, converts them to lists of integers, and then uses `Operation.buildlut/1` to generate the gradient. The output is cast to `uchar` and resized. ```Elixir defmodule Vix.KinoUtils do # Utility to read color and parse hex string into list of 8-bit integers def read_colors do start_color = Kino.Input.color("Start", default: "#DDDD55") end_color = Kino.Input.color("End", default: "#FF2200") [start_color, end_color] |> Kino.Layout.grid(columns: 6) |> Kino.render() start_color = read(start_color) end_color = read(end_color) {start_color, end_color} end defp read(input) do "#" <> color = Kino.Input.read(input) for <> do String.to_integer(hex, 16) end end end # Read user input for start and end colors {start_color, end_color} = Vix.KinoUtils.read_colors() # Create a matrix image with start and end colors {:ok, mat} = Image.new_matrix_from_array(4, 2, [[0 | start_color], [255 | end_color]]) # Generate gradient, cast to uchar, and resize mat |> Operation.buildlut!() |> Operation.cast!(:VIPS_FORMAT_UCHAR) |> Operation.resize!(3, vscale: 50) ``` -------------------------------- ### Get Installed libvips Version Source: https://hexdocs.pm/vix/Vix Retrieves the installed version of the libvips library. This function returns the version as a string, which can be helpful for compatibility checks or reporting. The return type is a String. ```Elixir @spec version() :: String.t() ``` -------------------------------- ### Resize and Scale Images Source: https://hexdocs.pm/vix/introduction Provides examples for resizing and scaling images using Vix. Includes fast thumbnail generation, high-quality resizing with Lanczos3, scaling to specific dimensions while maintaining aspect ratio, and smart cropping. ```Elixir # Fast thumbnail generation - optimized for speed, perfect for preview generation thumbnail=Operation.thumbnail_image!(image,400) # For even better performance use `Operation.thumbnail!` and pass path directly # thumbnail = Operation.thumbnail!("input.jpg", 300) # High-quality resize with Lanczos3 kernel - best for preserving image quality # Lanczos3 provides excellent results for both upscaling and downscaling resized=Operation.resize!(image,0.5,kernel::VIPS_KERNEL_LANCZOS3) # Scale to specific dimensions while maintaining proper aspect ratio # Useful for fitting images into specific containers while preventing distortions scaled=Operation.resize!(image,400/Image.width(image),vscale:300/Image.height(image)) # Smart cropping - uses edge detection and entropy analysis to keep important parts # Perfect for automated content-aware thumbnail generation {smart_crop,_}=Operation.smartcrop!(image,300,200) show([thumbnail,resized,scaled,smart_crop],2) ``` -------------------------------- ### Example: Manipulate and Display an Image Source: https://hexdocs.pm/vix/picture-language Demonstrates loading an image from a file, applying a corner split operation, arranging the split image using `below` and `horz_flip`, and finally displaying the result using the `show` helper function. ```elixir alias Vix.Vips.Image import VixExt {:ok, img} = Image.new_from_file("~/Downloads/kitty.png") img = PictUtils.corner_split(img, 5) right = Pict.below(img, Pict.vert_flip(img)) left = Pict.horz_flip(right) img = Pict.beside(left, right) show(img) ``` -------------------------------- ### Resize Image with Vix.Vips.Operation Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Demonstrates loading and resizing an image to a specified width while maintaining the aspect ratio. This is a basic example using the Vix.Vips.Operation module. ```Elixir {:ok, image} = Vix.Vips.Operation.load("image.jpg") {:ok, resized_image} = Vix.Vips.Operation.resize(image, width: 500) ``` -------------------------------- ### Helper Module for Fetching and Displaying Images Source: https://hexdocs.pm/vix/introduction Defines an ImageHelper module with functions to fetch sample images from a URL using Req and Vix, and to display images or a grid of images using Kino. This facilitates practical examples. ```Elixir defmodule ImageHelper do def get_sample_image(width, height) do response = Req.get!("https://picsum.photos/#{width}/#{height}", decode_body: false) {:ok, image} = Vix.Vips.Image.new_from_buffer(response.body) image end def show(img, columns \ nil) when is_struct(img, Vix.Vips.Image) do show([img], columns) end def show(images, columns) when is_list(images) do columns = columns || length(images) images |> Kino.Layout.grid(boxed: true, columns: columns) |> Kino.render() end end ``` -------------------------------- ### Install Vix and Kino Dependencies Source: https://hexdocs.pm/vix/auto_correct_rotation Installs the necessary Elixir dependencies, Vix and Kino, for image processing. It also configures Vix to use the platform-provided libvips, which is necessary for operations like Fourier Transforms that rely on external libraries. ```Elixir Mix.install([{:vix,"~> 0.17.0"},{:kino,"~> 0.9.2"}], # pre-built binaries does not support fourier transform operations # since these operations depend on an additional library. # Usually the platform/OS provided libvips comes with these additional library # so we are telling vix to use the libvips provided by the platform # and compile NIF for that. Follow platform specific libvips # installation guides system_env:[{"VIX_COMPILATION_MODE","PLATFORM_PROVIDED_LIBVIPS"}] ) ``` -------------------------------- ### Advanced Smart Thumbnailing Source: https://hexdocs.pm/vix/readme This example provides a more detailed use of the smart thumbnail operation, specifying `VIPS_SIZE_DOWN` to only downsize the image and `VIPS_INTERESTING_ATTENTION` to focus on salient features. ```Elixir # Smart thumbnail preserving important features {:ok, thumb} = Operation.thumbnail("large.jpg", 300, size::VIPS_SIZE_DOWN, # only downsize, it will just copy if asked to upsize crop::VIPS_INTERESTING_ATTENTION) ``` -------------------------------- ### Access Image Channels and Regions Source: https://hexdocs.pm/vix/introduction Explains how Vix implements Elixir's Access protocol for manipulating image channels and regions. Examples include getting specific color channels, extracting pixel squares, and rearranging color channels. ```Elixir # Get the red channel from an RGB image # Useful for channel-specific analysis or effects red = image[0] # Get a 200x100 pixel square from the top-left corner # Perfect for creating image tiles or focusing on specific regions top_left = image[[0..199, 0..99]] # Get the bottom-right 200x100 pixel square # Negative indices count from the end, just like in Elixir lists bottom_right = image[[-200..-1, -100..-1]] # Alternatively you can use keyword list for more readable code # Get a 200x100 pixel square from the top-left corner, and only red-green channels red_top_left = image[[width: 0..199, height: 0..99, band: 0..1]] show([top_left, bottom_right, red_top_left]) # Rearrange color channels - useful for color space manipulation # RGB -> GBR: Swapping channels can create interesting color effects remaped = Operation.bandjoin!([image[1], image[2], image[0]]) show([red, remaped]) ``` -------------------------------- ### Configure Vix Compilation with System libvips Source: https://hexdocs.pm/vix/readme Configures Vix to use the system's libvips during compilation. This is an advanced setup option for users who prefer to manage libvips separately. ```Shell export VIX_COMPILATION_MODE=PLATFORM_PROVIDED_LIBVIPS ``` -------------------------------- ### Generate HSV Rainbow Colors with buildlut Source: https://hexdocs.pm/vix/rainbow This example demonstrates generating a rainbow color spectrum in HSV color space using `Operation.buildlut/1`. It creates a matrix with HSV values for red and violet, applies `buildlut`, and then copies the image, setting the band format to `uchar` and interpretation to `HSV`. The result is resized for visibility. ```Elixir aliasVix.Vips.Image aliasVix.Vips.Operation # Create a matrix image with HSV values for red and violet {:ok, mat} = Image.new_matrix_from_array(4, 2, [ # position 0 - [0, 255, 255] (Red in HSV) [0, 0, 255, 255], # position 255 - [255, 255, 255] (Violet in HSV) [255, 255, 255, 255] ]) # Generate the gradient gradient = Operation.buildlut!(mat) # Copy the gradient, set colorspace to HSV and band format to uchar rainbow_colors = Operation.copy!(gradient, band_format: :VIPS_FORMAT_UCHAR, interpretation: :VIPS_INTERPRETATION_HSV) # Resize for visibility Operation.resize!(rainbow_colors, 3, vscale: 50) ``` -------------------------------- ### Create Instagram-style Filters with Vix Source: https://hexdocs.pm/vix/introduction Provides examples of creating custom image filters, including a 'vintage' filter with color adjustments and blur, and a 'dramatic' filter with contrast and sharpening. It also shows how to apply a vignette effect. ```Elixir defmodule PhotoFilters do def vintage(image) do image # Adjust color balance for warm, aged look |> Operation.linear!([0.9, 0.7, 0.6], [-0.1, 0.1, 0.2]) # Add subtle blur to soften details |> Operation.gaussblur!(0.5) # Enhance contrast for dramatic effect |> Operation.linear!([1.2], [-0.1]) end def dramatic(image) do # Create vignette mask using Gaussian distribution # This darkens the edges while keeping the center bright mask = Operation.gaussmat!(Image.width(image), 0.5, min: 0, max: 0.8) image # Increase contrast significantly |> Operation.linear!([1.4], [-0.2]) # Enhance edge details for cinematic look |> Operation.sharpen!(sigma: 1.0, x1: 2.0) # Apply vignette effect using overlay blend |> Operation.composite2!(mask, :VIPS_BLEND_MODE_OVERLAY) end end # Apply our custom filters to sample image vintage_photo = PhotoFilters.vintage(image) dramatic_photo = PhotoFilters.dramatic(image) show([vintage_photo, dramatic_photo]) copy ``` -------------------------------- ### Get Max Cached Files Source: https://hexdocs.pm/vix/Vix Retrieves the maximum number of tracked files allowed before cached operations start being dropped. libvips only tracks file descriptors it allocates. ```Elixir cache_get_max_files() @spec cache_get_max_files() :: integer() ``` -------------------------------- ### Vix Image Loading and Creation Source: https://hexdocs.pm/vix/introduction Illustrates different methods for creating Vix Image structs: loading from a file path, loading from a binary buffer (useful for HTTP responses or uploaded files), and building a solid color image. ```Elixir alias Vix.Vips.Image alias Vix.Vips.Operation # 1. Loading from file. Change the image path # {:ok, from_file} = Image.new_from_file("input.jpg") # 2. Loading from memory - useful for handling uploaded files or HTTP responses # image_binary = File.read!("input.jpg") # {:ok, from_binary} = Image.new_from_buffer(image_binary) # 3. Creating a solid color image - useful for backgrounds or overlays red = Image.build_image!(100, 100, [255, 0, 0]) # Vix implements `Kino.Render` protocol, so you can see the image by just # returning it for the Livebook cell. ``` -------------------------------- ### Get Current Memory Allocation (libvips) Source: https://hexdocs.pm/vix/Vix Returns the number of bytes currently allocated by libvips. This value is used by libvips to determine when to start dropping cache. The function returns an integer representing the memory in bytes. ```Elixir @spec tracked_get_mem() :: integer() ``` -------------------------------- ### Load WebP from Buffer - webpload_buffer! Source: https://hexdocs.pm/vix/Vix.Vips Loads a WebP image from a binary buffer without returning an error tuple on failure, instead returning `no_return`. It accepts the same optional parameters as `webpload_buffer` for controlling the loading process. Returns the output image and associated flags. ```Elixir @spec webpload_buffer!(binary(), revalidate: boolean(), "fail-on": vips_fail_on(), access: vips_access(), memory: boolean(), scale: float(), n: integer(), page: integer()) :: {Vix.Vips.Image.t(), %{flags: vips_foreign_flags()}} | no_return() ``` -------------------------------- ### Get Component from Complex Image (Bang) with Vix Vips Source: https://hexdocs.pm/vix/Vix.Vips Retrieves a component from a complex image and returns the image directly or raises an error. It takes an input image and a 'get' argument. ```Elixir complexget!(input, get) ``` -------------------------------- ### Basic Image Resizing (Elixir) Source: https://hexdocs.pm/vix/Vix.Vips Demonstrates loading an image, resizing it by a scale factor, and saving the result. This involves creating a new image from a file, applying the resize operation, and writing the modified image to a new file. ```Elixir image = Vix.Vips.Image.new_from_file("input.jpg") resized = Operation.resize(image, scale: 0.5) Vix.Vips.Image.write_to_file(resized, "output.jpg") ``` -------------------------------- ### Get Component from Complex Image with Vix Vips Source: https://hexdocs.pm/vix/Vix.Vips Retrieves a component from a complex image. It accepts an input image and a 'get' argument specifying the component to extract. Returns an {:ok, Image.t()} on success or {:error, term()} on failure. ```Elixir complexget(input, get) ``` -------------------------------- ### Load WebP Images with Vix Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Loads WebP images using the Vix.Vips.Operation module. Allows scaling, specifying the number of pages, and the first page to load. Options include forcing memory open and scaling factors. ```Elixir Vix.Vips.Operation.webpload/2 Vix.Vips.Operation.webpload!/2 Vix.Vips.Operation.webpload_buffer!/2 ``` -------------------------------- ### Generate Grayscale Gradient with buildlut Source: https://hexdocs.pm/vix/rainbow Demonstrates generating a simple grayscale gradient using `Operation.buildlut/1`. It involves creating a matrix image from an array and then applying `buildlut` to create the gradient. The resulting gradient can be resized for better visualization. ```Elixir aliasVix.Vips.Image aliasVix.Vips.Operation # Create a matrix image from an array: [[0,0], [255,255]] {:ok, mat} = Image.new_matrix_from_array(2, 2, [[0, 0], [255, 255]]) # Generate the gradient using buildlut gradient = Operation.buildlut!(mat) # Resize the gradient for visualization Operation.resize!(gradient, 3, vscale: 50) ``` -------------------------------- ### Get Component from Complex Image Source: https://hexdocs.pm/vix/Vix.Vips Retrieves a specific component from a complex-valued image. The operation can be performed in-place. ```Image Processing complexget(input, get) complexget!(input, get) ``` -------------------------------- ### Vips Image Loading Source: https://hexdocs.pm/vix/license Loads images using the Vips library. `vipsload/2` loads from a file, and `vipsload!/2` loads in-place. ```Elixir vipsload/2 vipsload!/2 ``` -------------------------------- ### Get Concurrency Source: https://hexdocs.pm/vix/Vix Returns the number of worker threads that libvips should use when running a VipsThreadPool. The value is clipped to the range 1-1024. ```Elixir concurrency_get() @spec concurrency_get() :: integer() ``` -------------------------------- ### Load WebP from File - webpload! Source: https://hexdocs.pm/vix/Vix.Vips Loads a WebP image from a specified file path. Supports various options to control caching, error handling, access patterns, memory usage, scaling, and page selection. Returns the output image and associated flags. ```Elixir @spec webpload!(String.t(), revalidate: boolean(), "fail-on": vips_fail_on(), access: vips_access(), memory: boolean(), scale: float(), n: integer(), page: integer()) :: {Vix.Vips.Image.t(), %{flags: vips_foreign_flags()}} | no_return() ``` -------------------------------- ### Get Supported Saver Suffixes Source: https://hexdocs.pm/vix/search_q=save+buffer+-filename+-profile Returns a list of supported file extensions for saving images. This function is part of the Vix.Vips.Image module. ```elixir Vix.Vips.Image.supported_saver_suffixes/0 ``` -------------------------------- ### Get Max Cache Operations Source: https://hexdocs.pm/vix/Vix Retrieves the maximum number of operations that are kept in the cache. This function is part of the cache management system for libvips. ```Elixir cache_get_max() @spec cache_get_max() :: integer() ``` -------------------------------- ### Import ICC Profile (Vix) Source: https://hexdocs.pm/vix/Vix.Vips Imports an image from a device using an ICC profile. Supports optional parameters like `input-profile`, `embedded`, `black-point-compensation`, `intent`, and `pcs`. Returns an {:ok, image} tuple or an {:error, reason}. ```Elixir icc_import(input, input_profile: nil, embedded: false, black_point_compensation: false, intent: :VIPS_INTENT_RELATIVE, pcs: :VIPS_PCS_LAB) ``` -------------------------------- ### Load WebP from Buffer Source: https://hexdocs.pm/vix/Vix.Vips Loads a WebP image from a buffer. Accepts a buffer and optional parameters. ```vips webpload_buffer(buffer, optional \ []) ``` ```vips webpload_buffer!(buffer, optional \ []) ``` -------------------------------- ### Get Absolute Value of Image (Exclamation) Source: https://hexdocs.pm/vix/Vix.Vips Calculates the absolute value of an image, raising an error on failure. It takes an input image and returns the processed image. ```Elixir @spec abs!(Vix.Vips.Image.t()) :: Vix.Vips.Image.t() | no_return() ``` -------------------------------- ### Create Text Images with Vix Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Creates images from text using the Vix.Vips.Operation module. Supports specifying font files, text wrapping, RGBA output, line spacing, and DPI. Options include loading font files and setting text properties. ```Elixir Vix.Vips.Operation.text/2 Vix.Vips.Operation.text!/2 ``` -------------------------------- ### Load WebP from Buffer - webpload_buffer Source: https://hexdocs.pm/vix/Vix.Vips Loads a WebP image from a binary buffer. This function allows for loading images directly from memory, offering options similar to file loading for caching, error handling, and image parameters. Returns an :ok tuple with the image and flags on success, or an :error tuple on failure. ```Elixir @spec webpload_buffer(binary(), revalidate: boolean(), "fail-on": vips_fail_on(), access: vips_access(), memory: boolean(), scale: float(), n: integer(), page: integer()) :: {:ok, {Vix.Vips.Image.t(), %{flags: vips_foreign_flags()}}} | {:error, term()} ``` -------------------------------- ### Complex Get Operation Source: https://hexdocs.pm/vix/Vix.Vips Extracts real and imaginary parts from a complex image. 'complexget/2' returns new images, and 'complexget!/2' modifies the image in place. ```elixir Vix.Vips.Operation.complexget/2 Vix.Vips.Operation.complexget!/2 ``` -------------------------------- ### Complex Get Operation Source: https://hexdocs.pm/vix/search_q=save+buffer+-filename+-profile Extracts real and imaginary parts from a complex image. 'complexget/2' returns new images, and 'complexget!/2' modifies the image in place. ```elixir Vix.Vips.Operation.complexget/2 Vix.Vips.Operation.complexget!/2 ``` -------------------------------- ### System Command Execution Source: https://hexdocs.pm/vix/license Executes a system command. `system/2` returns the command output, and `system!/2` executes it in-place. ```Elixir system/2 system!/2 ``` -------------------------------- ### Get Supported Saver Suffixes - Vix.Vips.Image.supported_saver_suffixes Source: https://hexdocs.pm/vix/search_q=save+-buffer+-filename+-profile Returns a list of supported extensions for saving images. These suffixes can be used to specify the image format during the saving process. ```Elixir Vix.Vips.Image.supported_saver_suffixes/0 ``` -------------------------------- ### Complex Get Operation Source: https://hexdocs.pm/vix/license Extracts real and imaginary parts from a complex image. 'complexget/2' returns new images, and 'complexget!/2' modifies the image in place. ```elixir Vix.Vips.Operation.complexget/2 Vix.Vips.Operation.complexget!/2 ``` -------------------------------- ### Image Resizing and Cropping Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile This snippet includes functions related to image resizing and cropping, such as `extract_area` for extracting a region and `region_shrink` for resizing. It also covers operations like `affine` for geometric transformations. ```elixir affine/3 affine!/3 extract_area/5 extract_area!/5 region_shrink/2 region_shrink!/2 resize/3 resize!/3 ``` -------------------------------- ### Get Max Cached Memory Source: https://hexdocs.pm/vix/Vix Retrieves the maximum amount of tracked memory allowed before cached operations are dropped. libvips only tracks file descriptors it allocates. ```Elixir cache_get_max_mem() @spec cache_get_max_mem() :: integer() ``` -------------------------------- ### Complex Get Operation Source: https://hexdocs.pm/vix/Vix.Vips.Image Extracts real and imaginary parts from a complex image. 'complexget/2' returns new images, and 'complexget!/2' modifies the image in place. ```elixir Vix.Vips.Operation.complexget/2 Vix.Vips.Operation.complexget!/2 ``` -------------------------------- ### Build Tone Lookup Table with tonelut! Source: https://hexdocs.pm/vix/Vix.Vips Builds a lookup table (LUT) for tone adjustment, similar to tonelut but raises an error on failure. It allows fine-tuning of highlights, mid-tones, and shadows with configurable input and output ranges. The function returns the LUT image. ```Elixir @spec tonelut!( H: float(), M: float(), S: float(), Ph: float(), Pm: float(), Ps: float(), Lw: float(), Lb: float(), "out-max": integer(), "in-max": integer() ) :: Vix.Vips.Image.t() | no_return() ``` -------------------------------- ### Build Look-up Table Source: https://hexdocs.pm/vix/Vix.Vips Builds a look-up table. Accepts optional parameters. ```vips tonelut(optional \ []) ``` ```vips tonelut!(optional \ []) ``` -------------------------------- ### Get Absolute Value of Image Source: https://hexdocs.pm/vix/Vix.Vips Calculates the absolute value of an image. It takes an input image and returns either an ok tuple with the processed image or an error tuple. ```Elixir @spec abs(Vix.Vips.Image.t()) :: {:ok, Vix.Vips.Image.t()} | {:error, term()} ``` -------------------------------- ### Get Supported Saver Suffixes with Vix.Vips.Image.supported_saver_suffixes/0 Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Retrieves the image formats supported for saving. This function highlights that the format supported for saving might differ from the format supported for loading, such as SVG. ```Elixir Vix.Vips.Image.supported_saver_suffixes/0 ``` -------------------------------- ### Vix.Vips.Image Basic Usage and Access Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Demonstrates basic usage and access methods for images within the Vix.Vips.Image module. This includes functions for retrieving image properties, manipulating pixels, and reading/writing image data. ```Elixir vips_image_functions = [ "bands/1", "build_image/4", "build_image!/3", "coding/1", "copy_memory/1", "fetch/2", "filename/1", "format/1", "get_pixel/3", "get_pixel!/3", "has_alpha?/1", "header_field_names/1", "header_value/2", "header_value_as_string/2", "headers/1", "height/1", "interpretation/1", "mode/1", "mutate/2", "n_pages/1", "new_from_binary/5", "new_from_buffer/2", "new_from_enum/2", "new_from_file/1", "new_from_file/2", "new_from_image/2", "new_from_list/2", "new_matrix_from_array/4", "new_temp_file/1", "offset/1", "orientation/1", "page_height/1", "scale/1", "shape/1", "supported_saver_suffixes/0", "to_list/1", "to_list!/1", "width/1", "write_to_binary/1", "write_to_buffer/2", "write_to_buffer/3", "write_to_file/2", "write_to_file/3", "write_to_stream/2", "write_to_stream/3", "write_to_tensor/1", "xoffset/1", "xres/1", "yoffset/1", "yres/1" ] vips_image_types = ["t/0"] ``` -------------------------------- ### Get Image Metadata Source: https://hexdocs.pm/vix/introduction Demonstrates how to retrieve image metadata, including all available fields, specific field values, and image dimensions (width, height, bands). This is useful for debugging and understanding image characteristics. ```Elixir # Get all available metadata fields - useful for debugging and understanding image characteristics {:ok,fields}=Image.header_field_names(image) IO.puts("Available fields: #{Enum.join(fields,", ")}") # Get specific field value - useful for understanding image format and processing history {:ok,value}=Image.header_value(image,"vips-loader") IO.puts("Loader used: #{value}") # Get image dimensions and number of color channels - essential for proper image manipulation {width,height,bands}=Image.shape(image) ``` -------------------------------- ### Operator Overloading for Image Manipulation Source: https://hexdocs.pm/vix/introduction Demonstrates Vix's operator overloading for common image manipulations like adjusting brightness. It shows how multiplication scales pixel values and how operators can be combined for complex effects. ```Elixir use Vix.Operator, only: [+: 2, -: 2, *: 2] # Import specific operators # Adjust brightness using operators - multiplication scales pixel values brighter = image * 1.2 # Increase brightness by 20% darker = image * 0.8 # Decrease brightness by 20% # Combining operators for complex effects # This creates an enhanced image with adjusted brightness, contrast, and blur enhanced = (image * 1.2) - 10 + Operation.gaussblur!(image, 2) show([brighter, darker, enhanced]) ``` -------------------------------- ### Load PNG from Buffer (Success) Source: https://hexdocs.pm/vix/Vix.Vips Loads a PNG image from a binary buffer. Supports options like revalidation, fail-on level, access pattern, memory usage, and unlimited operations. Returns an :ok tuple with the image and flags, or an :error tuple. ```Elixir @spec pngload_buffer(binary(), revalidate: boolean(), "fail-on": vips_fail_on(), access: vips_access(), memory: boolean(), unlimited: boolean() ) :: {:ok, {Vix.Vips.Image.t(), %{flags: vips_foreign_flags()}}} | {:error, term()} ``` -------------------------------- ### Web Image Optimization: WebP, JPEG, AVIF Source: https://hexdocs.pm/vix/readme This code illustrates how to optimize images for the web by converting them to different formats like WebP, JPEG, and AVIF, with options for quality, effort, and stripping metadata. ```Elixir # Convert to WebP with quality optimization :ok = Image.write_to_file(img, "output.webp", Q: 80, effort: 4) # Create progressive JPEG with metadata stripped :ok = Image.write_to_file(img, "output.jpg", interlace: true, strip: true, Q: 85) # Generate multiple formats :ok = Image.write_to_file(img, "photo.avif", Q: 60) :ok = Image.write_to_file(img, "photo.webp", Q: 80) :ok = Image.write_to_file(img, "photo.jpg", Q: 85) ``` -------------------------------- ### WebP Image Loading Source: https://hexdocs.pm/vix/license Loads WebP images from a file or buffer. `webpload/2` loads from a file, `webpload_buffer/2` from a buffer. The `!` variants modify the image in-place. ```Elixir webpload/2 webpload!/2 webpload_buffer/2 webpload_buffer!/2 ``` -------------------------------- ### Get Peak Memory Allocation (libvips) Source: https://hexdocs.pm/vix/Vix Returns the largest number of bytes simultaneously allocated via libvips. This is useful for estimating the maximum memory requirements for a program. The function returns an integer representing the peak memory in bytes. ```Elixir @spec tracked_get_mem_highwater() :: integer() ``` -------------------------------- ### Generate Thumbnail from Buffer Source: https://hexdocs.pm/vix/Vix.Vips Creates a thumbnail from a buffer. Requires buffer and width, with optional parameters. ```vips thumbnail_buffer(buffer, width, optional \ []) ``` ```vips thumbnail_buffer!(buffer, width, optional \ []) ``` -------------------------------- ### Load HEIF Images with Vix Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Loads HEIF images using the Vix.Vips.Operation module. Supports fetching thumbnails, specifying the number of pages, and the first page to load. Options include forcing memory open and thumbnail selection. ```Elixir Vix.Vips.Operation.heifload/2 Vix.Vips.Operation.heifload!/2 Vix.Vips.Operation.heifload_buffer!/2 ``` -------------------------------- ### Find Angle from Cartesian Image (Elixir) Source: https://hexdocs.pm/vix/auto_correct_rotation Calculates the angle of an image by finding the row with the maximum value in its Cartesian representation. It uses Libvips' `project!` to get row sums and `max!` to find the position of the maximum value. The result is the angle in degrees. ```Elixir defmodule Utils do deffind_angle(cartesian) do # find the row wise and column wise sum # returns 2 images with respective column/row sum {_columns, rows} = Operation.project!(cartesian) # find position of the row with maximum value {_, %{y: y_pos}} = Operation.max!(rows) # convert the y position back to angle. y_pos / Image.height(rows) * 360 end end samples |> Enum.flat_map(fn img -> ft = Operation.spectrum!(img) cartesian = ComplexOps.to_cartesian(ft) angle = Utils.find_angle(cartesian) # print angle next to image text = Kino.Text.new("\n\n\n#{to_string(angle)}") [img, ft, cartesian, text] end) |> then(fn list -> headers = ~w(Input Fourier-Transform Polar-Plane Angle) |> Enum.map(&Kino.Text.new/1) headers ++ list end) |> Kino.Layout.grid(columns: 4) copy ``` -------------------------------- ### Run External Command with Vix Source: https://hexdocs.pm/vix/Vix.Vips Executes an external command, processing input and output images. Supports specifying input and output formats and capturing command logs. Returns an :ok tuple with results or an error. ```Elixir @spec system(String.t(), "in-format": String.t(), "out-format": String.t(), in: [Vix.Vips.Image.t()] ) :: {:ok, {%{log: String.t(), out: Vix.Vips.Image.t()}}} | {:error, term()} # Run an external command ``` -------------------------------- ### Import ICC Profile (Vix, Bang!) Source: https://hexdocs.pm/vix/Vix.Vips Imports an image from a device using an ICC profile, raising an error on failure. This is a non-returning version of `icc_import/2`. ```Elixir icc_import!(input, input_profile: nil, embedded: false, black_point_compensation: false, intent: :VIPS_INTENT_RELATIVE, pcs: :VIPS_PCS_LAB) ``` -------------------------------- ### Professional Text Overlay and Image Composition Source: https://hexdocs.pm/vix/introduction Shows how to overlay text onto images with proper DPI handling and alpha channel management for professional results. It includes positioning text and blending it with the base image using alpha composition. ```Elixir # Create high-quality text overlay with anti-aliasing {text,_} = Operation.text!("Hello from Vix!", width: 400, dpi: 300, # High DPI ensures sharp text at any size font: "sans-serif bold", rgba: true # Alpha channel enables smooth blending) # Position text precisely on the image # The embed operation handles proper padding and positioning positioned_text = Operation.embed!(text, 50, # X offset from left 50, # Y offset from top Image.width(image), Image.height(image)) # Blend using alpha composition for professional results composite = Operation.composite2!(image, positioned_text, :VIPS_BLEND_MODE_OVER) show([text, composite]) ``` -------------------------------- ### Load and Prepare Image for Processing Source: https://hexdocs.pm/vix/auto_correct_rotation Loads an image from a given URL using httpc, converts it to grayscale, and skips the alpha channel. This prepares the image for further processing, such as Fourier transformations, by ensuring it has the correct format and color space. ```Elixir alias Vix.Vips.Image alias Vix.Vips.Operation # import convenience math operators `+`, `-`, `*` etc. use Vix.Operator # we use :httpc to download the image {:ok, _} = Application.ensure_all_started(:inets) {:ok, _} = Application.ensure_all_started(:ssl) # image link is from the stackoverflow question image_url = 'https://i.stack.imgur.com/2q4Qr.png' {:ok, {{_, 200, _}, _headers, bin}} = :httpc.request(:get, {image_url, []}, [:timeout: 5000], []) {:ok, img} = bin |> IO.iodata_to_binary() |> Image.new_from_buffer() # convert 4 channel PNG image to black & white img = Operation.colourspace!(img, :VIPS_INTERPRETATION_B_W) # skip alpha band img = img[0] ``` -------------------------------- ### Build Tone Lookup Table with tonelut Source: https://hexdocs.pm/vix/Vix.Vips Builds a lookup table (LUT) to adjust image tones, allowing modifications to highlights, mid-tones, and shadows. It supports custom input and output ranges and returns an :ok tuple with the LUT image or an error. ```Elixir @spec tonelut( H: float(), M: float(), S: float(), Ph: float(), Pm: float(), Ps: float(), Lw: float(), Lb: float(), "out-max": integer(), "in-max": integer() ) :: {:ok, Vix.Vips.Image.t()} | {:error, term()} ``` -------------------------------- ### Smart Thumbnail Generation Source: https://hexdocs.pm/vix/readme Demonstrates how to create a smart thumbnail that preserves important features of the original image. This is useful for ensuring key elements are visible even after resizing. ```Elixir # Smart thumbnail (preserves important features) {:ok, thumb} = Operation.thumbnail("large.jpg", 300, size::VIPS_SIZE_DOWN, crop::VIPS_INTERESTING_ATTENTION) ``` -------------------------------- ### Generate Thumbnail from File Source: https://hexdocs.pm/vix/Vix.Vips Creates a thumbnail from a file. Requires filename and width, with optional parameters. ```vips thumbnail(filename, width, optional \ []) ``` ```vips thumbnail!(filename, width, optional \ []) ``` -------------------------------- ### Load Image from File with Vix.Vips.Image.new_from_file/2 Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Provides a high-level interface to load images from various formats. It optimizes loading by initially reading only the image header. ```Elixir Image.new_from_file("path/to/image.jpg") ``` ```Elixir Image.new_from_file("photo.jpg") ``` ```Elixir Image.new_from_file("path/to/image.jpg", downsample: 2) ``` -------------------------------- ### Load GIF Images with Vix Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Loads GIF images using the Vix.Vips.Operation module. Supports loading from memory, specifying the first page, and the number of pages to load. Options include forcing memory open and selecting specific pages. ```Elixir Vix.Vips.Operation.gifload/2 Vix.Vips.Operation.gifload!/2 Vix.Vips.Operation.gifload_buffer!/2 ``` -------------------------------- ### Build LUT Operation Source: https://hexdocs.pm/vix/Vix.Vips Builds a look-up table (LUT) for an image. 'buildlut/1' returns a new image, and 'buildlut!/1' modifies the image in place. ```elixir Vix.Vips.Operation.buildlut/1 Vix.Vips.Operation.buildlut!/1 ``` -------------------------------- ### Generate Thumbnail from Buffer (Elixir) Source: https://hexdocs.pm/vix/Vix.Vips Creates a thumbnail from a given buffer. It accepts various optional parameters to control the resizing process, such as width, height, and cropping behavior. The function returns a Vix.Vips.Image.t() or no_return(). ```Elixir @spec thumbnail_buffer!(binary(), integer(), "fail-on": vips_fail_on(), intent: vips_intent(), "output-profile": String.t(), "input-profile": String.t(), linear: boolean(), crop: vips_interesting(), "no-rotate": boolean(), size: vips_size(), height: integer(), "option-string": String.t() ) :: Vix.Vips.Image.t() | no_return() ``` -------------------------------- ### Vix.Vips.Image Basic Usage and Access Source: https://hexdocs.pm/vix/introduction Demonstrates basic usage and access methods for images within the Vix.Vips.Image module. This includes functions for retrieving image properties, manipulating pixels, and reading/writing image data. ```Elixir vips_image_functions = [ "bands/1", "build_image/4", "build_image!/3", "coding/1", "copy_memory/1", "fetch/2", "filename/1", "format/1", "get_pixel/3", "get_pixel!/3", "has_alpha?/1", "header_field_names/1", "header_value/2", "header_value_as_string/2", "headers/1", "height/1", "interpretation/1", "mode/1", "mutate/2", "n_pages/1", "new_from_binary/5", "new_from_buffer/2", "new_from_enum/2", "new_from_file/1", "new_from_file/2", "new_from_image/2", "new_from_list/2", "new_matrix_from_array/4", "new_temp_file/1", "offset/1", "orientation/1", "page_height/1", "scale/1", "shape/1", "supported_saver_suffixes/0", "to_list/1", "to_list!/1", "width/1", "write_to_binary/1", "write_to_buffer/2", "write_to_buffer/3", "write_to_file/2", "write_to_file/3", "write_to_stream/2", "write_to_stream/3", "write_to_tensor/1", "xoffset/1", "xres/1", "yoffset/1", "yres/1" ] vips_image_types = ["t/0"] ``` -------------------------------- ### Vix.Vips.Interpolate Initialization Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Details the initialization functions for the Vix.Vips.Interpolate module. This module likely handles interpolation methods used in image processing operations. ```Elixir vips_interpolate_functions = ["new/1", "new!/1"] vips_interpolate_types = ["t/0"] ``` -------------------------------- ### Edge Detection and Gradient Functions Source: https://hexdocs.pm/vix/search_q=load+-buffer+-filename+-profile Functions for detecting edges and calculating image gradients using common operators like Prewitt and Scharr. ```Erlang prewitt/1 prewitt!/1 scharr/1 scharr!/1 ```