### Install vipsgen Go Package Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Use 'go get' to install the vipsgen library. Ensure libvips 8.10+ is installed on your system. ```bash go get github.com/cshum/vipsgen/vips ``` -------------------------------- ### Installing vipsgen Source: https://github.com/cshum/vipsgen/blob/main/README.md Install the vipsgen command-line tool using `go install`. Ensure your Go environment is set up correctly. ```bash go install github.com/cshum/vipsgen/cmd/vipsgen@latest ``` -------------------------------- ### Get vipsgen Go package Source: https://github.com/cshum/vipsgen/blob/main/README.md Install the pre-generated vipsgen Go package using 'go get'. ```bash go get -u github.com/cshum/vipsgen/vips ``` -------------------------------- ### Install libvips on Debian/Ubuntu Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Install libvips-dev and pkg-config on Debian/Ubuntu systems using apt-get. ```bash # Linux (Debian/Ubuntu) sudo apt-get install libvips-dev pkg-config ``` -------------------------------- ### Install vips and pkg-config with Homebrew Source: https://github.com/cshum/vipsgen/blob/main/README.md Use Homebrew to install the necessary dependencies for vipsgen on macOS. ```bash brew install vips pkg-config ``` -------------------------------- ### Install libvips on CentOS/RHEL Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Install vips-devel and pkg-config on CentOS/RHEL systems using yum. ```bash # Linux (CentOS/RHEL) sudo yum install vips-devel pkg-config ``` -------------------------------- ### Install libvips on Debian/Ubuntu Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Install the libvips development headers and pkg-config on Debian-based systems using apt-get. This is a prerequisite for building vipsgen on Linux. ```bash # Debian/Ubuntu sudo apt-get install libvips-dev pkg-config ``` -------------------------------- ### Print libvips Version Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Example of how to print the libvips version using the MajorVersion, MinorVersion, and MicroVersion constants. ```go fmt.Printf("libvips %s.%s.%s\n", vips.MajorVersion, vips.MinorVersion, vips.MicroVersion) ``` -------------------------------- ### Load PNG from Source Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Loads a PNG image from a source stream. No specific options are shown in this example. ```go source := vips.NewSource(file) defersource.Close() image, err := vips.NewPngloadSource(source, nil) ``` -------------------------------- ### Install libvips on Alpine Linux Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Install the libvips development headers and pkg-config on Alpine Linux using apk. This is a prerequisite for building vipsgen on Alpine. ```bash # Alpine apk add vips-dev ``` -------------------------------- ### Install libvips on CentOS/RHEL Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Install the libvips development headers and pkg-config on CentOS/RHEL systems using yum. This is a prerequisite for building vipsgen on Linux. ```bash # CentOS/RHEL sudo yum install vips-devel pkg-config ``` -------------------------------- ### Install libvips on macOS Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Install libvips and pkg-config using Homebrew for macOS users. ```bash # macOS brew install vips pkg-config ``` -------------------------------- ### Example Custom Logging Handler Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md An example of setting a custom logging handler that formats and prints log messages using the standard log package. It sets the verbosity level to Debug. ```go vips.SetLogging(func(domain string, level vips.LogLevel, message string) { log.Printf("[%s] %s: %s", domain, level, message) }, vips.LogLevelDebug) ``` -------------------------------- ### Process and save an image using vipsgen Source: https://github.com/cshum/vipsgen/blob/main/README.md This example demonstrates fetching an image, creating a thumbnail with options, adding a border, and saving the result as a WebP file. Ensure the source body is closed after image processing and images are closed to free memory. ```go package main import ( "log" "net/http" "github.com/cshum/vipsgen/vips" ) func main() { // Fetch an image from http.Get resp, err := http.Get("https://raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png") if err != nil { log.Fatalf("Failed to fetch image: %v", err) } defer resp.Body.Close() // Create source from io.ReadCloser source := vips.NewSource(resp.Body) defer source.Close() // source needs to remain available during image lifetime // Shrink-on-load via creating image from thumbnail source with options image, err := vips.NewThumbnailSource(source, 800, &vips.ThumbnailSourceOptions{ Height: 1000, FailOn: vips.FailOnError, // Fail on first error }) if err != nil { log.Fatalf("Failed to load image: %v", err) } defer image.Close() // always close images to free memory // Add a yellow border using vips_embed border := 10 if err := image.Embed( border, border, image.Width()+border*2, image.Height()+border*2, &vips.EmbedOptions{ Extend: vips.ExtendBackground, // extend with colour from the background property Background: []float64{255, 255, 0, 255}, // Yellow border }, ); err != nil { log.Fatalf("Failed to add border: %v", err) } log.Printf("Processed image: %dx%d\n", image.Width(), image.Height()) // Save the result as WebP file with options err = image.Webpsave("resized-gopher.webp", &vips.WebpsaveOptions{ Q: 85, // Quality factor (0-100) Effort: 4, // Compression effort (0-6) SmartSubsample: true, // Better chroma subsampling }) if err != nil { log.Fatalf("Failed to save image as WebP: %v", err) } log.Println("Successfully saved processed images") } ``` -------------------------------- ### Using Options Structs for Operations Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Shows how to use options structs for operations that accept optional parameters. The first example uses default options, while the second provides custom values for Kernel and Gap. ```go // Basic usage (no options) image.Resize(0.5, nil) // With options image.Resize(0.5, &vips.ResizeOptions{ Kernel: vips.KernelLanczos3, Gap: 2.0, }) ``` -------------------------------- ### Check libvips Installation Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Use this command to check if libvips development headers are installed and accessible via pkg-config. If the output is empty, install the libvips development package. ```bash pkg-config --cflags --libs vips # If empty, install: apt-get install libvips-dev ``` -------------------------------- ### Create an Image Processing Pipeline Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Build a sequence of image operations by chaining method calls on an image object. This example demonstrates loading, resizing, flattening, and saving an image. ```go // Pipeline: Load -> Resize -> Threshold -> Save func pipeline(inPath, outPath string) error { // Load img1, _ := vips.NewImageFromFile(inPath, nil) defer img1.Close() // Resize img1.Resize(0.5, nil) // More operations can be chained img1.Flatten(nil) // Save return img1.Jpegsave(outPath, nil) } ``` -------------------------------- ### Check Installed libvips Version Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Use this command to determine the version of libvips installed on your system. This helps in choosing the appropriate pre-generated binding. ```bash vips --version ``` -------------------------------- ### Save PNG to Target Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Saves an image to a target stream in PNG format. No specific options are shown in this example. ```go target := vips.NewTarget(file) defersource.Close() err := image.PngsaveTarget(target, nil) ``` -------------------------------- ### Print Memory Statistics Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Example of reading and printing libvips memory and resource statistics using ReadVipsMemStats and the MemoryStats struct. ```go var stats vips.MemoryStats vips.ReadVipsMemStats(&stats) fmt.Printf("Memory: %d bytes\nHigh: %d bytes\nFiles: %d\nAllocs: %d\n", stats.Mem, stats.MemHigh, stats.Files, stats.Allocs) ``` -------------------------------- ### Create Default ResizeOptions Source: https://github.com/cshum/vipsgen/blob/main/README.md Provides default values for the vips_resize optional arguments. Call this function to get a pre-configured ResizeOptions struct. ```go // DefaultResizeOptions creates default value for vips_resize optional arguments func DefaultResizeOptions() *ResizeOptions { return &ResizeOptions{ Kernel: Kernel(5), Gap: 2, } } ``` -------------------------------- ### Importing vipsgen Packages Source: https://github.com/cshum/vipsgen/blob/main/README.md Import the appropriate vipsgen package based on your installed libvips version. Only import one package. Use the latest version (vips) if unsure. ```go // For libvips 8.18.x (latest - recommended) import "github.com/cshum/vipsgen/vips" // For libvips 8.17.x import "github.com/cshum/vipsgen/vips817" // For libvips 8.16.x import "github.com/cshum/vipsgen/vips816" func main() { // API is identical across all versions img, err := vips.NewImageFromFile("input.jpg", nil) if err != nil { log.Fatal(err) } defer img.Close() err = img.Resize(0.5, nil) // ... } ``` -------------------------------- ### Check libvips Version Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Verify the installed libvips version using the 'vips --version' command. Ensure it meets the minimum requirement of 8.10+ to avoid runtime panics. ```bash vips --version # Upgrade if needed ``` -------------------------------- ### Image Loading with Retry Logic Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md Implement retry logic for image loading to handle transient errors. This example uses exponential backoff with a maximum number of retries. ```go func loadImageWithRetry(path string, maxRetries int) (*vips.Image, error) { var lastErr error for i := 0; i < maxRetries; i++ { img, err := vips.NewImageFromFile(path, nil) if err == nil { return img, nil } lastErr = err if i < maxRetries-1 { time.Sleep(time.Duration(math.Pow(2, float64(i))) * time.Second) } } return nil, fmt.Errorf("failed after %d retries: %w", maxRetries, lastErr) } ``` -------------------------------- ### Get Image Format Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Detects and returns the image format (e.g., ImageTypeJpeg, ImageTypePng). This helps in identifying the file type. ```Go func (r *Image) Format() ImageType ``` -------------------------------- ### Configure Caching Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Configures the memory and file caches for VipsGen. This example sets the maximum cache memory to 100 MB and the maximum cache size to 1000 items. ```go vips.Startup(&vips.Config{ MaxCacheMem: 100 * 1024 * 1024, // 100 MB MaxCacheSize: 1000, }) ``` -------------------------------- ### Configure Concurrency Level Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Sets the number of threads for the thread pool at startup. This example configures VipsGen to use 4 threads for concurrent processing. ```go vips.Startup(&vips.Config{ ConcurrencyLevel: 4, // Use 4 threads }) ``` -------------------------------- ### Error Handling in Image Operations Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Emphasizes the necessity of checking for errors after image operations. This example shows how to check for errors when loading an image from a file. ```go image, err := vips.NewImageFromFile(path, nil) if err != nil { log.Fatalf("Failed to load image: %v", err) } ``` -------------------------------- ### Pixel-wise Image Addition Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/advanced-operations.md Adds two images pixel by pixel. Ensure both images have the same dimensions and compatible bands before performing the addition. The example demonstrates resizing the overlay image to match the background before addition. ```Go img1, _ := vips.NewImageFromFile("background.jpg", nil) img2, _ := vips.NewImageFromFile("overlay.jpg", nil) deffer img2.Close() // Ensure same size img2.Thumbnail(img1.Width(), &vips.ThumbnailOptions{ Height: img1.Height(), }) img1.Add(img2) // Pixel-wise addition img1.Jpegsave("result.jpg", nil) ``` -------------------------------- ### Initialize libvips with Configuration Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Call Startup before creating any images to initialize libvips and ensure version compatibility. It's safe to call multiple times. Configuration options can be provided to control concurrency and cache behavior. ```go vips.Startup(&vips.Config{ ConcurrencyLevel: 4, MaxCacheMem: 50 * 1024 * 1024, // 50MB }) defers vips.Shutdown() ``` -------------------------------- ### Streaming I/O with Source and Target Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/INDEX.md Demonstrates setting up streaming input and output using io.Reader and io.Writer interfaces with Vipsgen's Source and Target. ```go source := vips.NewSource(reader) target := vips.NewTarget(writer) ``` -------------------------------- ### Initialize Source with io.ReadCloser Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Always provide a valid io.ReadCloser to vips.NewSource. Passing nil will result in a panic or nil return. ```go source := vips.NewSource(nil) // Will panic or return nil ``` ```go reader := os.Open("file") // Check for error first if err != nil { return err } source := vips.NewSource(reader) defer source.Close() ``` -------------------------------- ### Image Resizing with Options Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/INDEX.md Demonstrates how to resize an image using the Resize method with optional parameters specified via a struct. ```go image.Resize(0.5, &vips.ResizeOptions{ Kernel: vips.KernelLanczos3, }) ``` -------------------------------- ### Explicitly Call vips.Startup Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md Call `vips.Startup` explicitly to catch potential libvips initialization errors early. This is useful if the automatic startup on the first image operation is not sufficient. ```go func init() { // Startup is called automatically on first image operation // To catch errors, call explicitly: vips.Startup(&vips.Config{ ConcurrencyLevel: 1, }) // If this panics, libvips installation is broken } ``` -------------------------------- ### Basic Image Resize and Save Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Load an image from a file, resize it to 50%, and save it as a WebP file with specified quality. Ensure to close the image object when done. ```go package main import ( "log" "github.com/cshum/vipsgen/vips" ) func main() { // Load image image, err := vips.NewImageFromFile("input.jpg", nil) if err != nil { log.Fatal(err) } defer image.Close() // Resize to 50% image.Resize(0.5, nil) // Save as WebP err = image.Webpsave("output.webp", &vips.WebpsaveOptions{Q: 85}) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Config Structure for libvips Startup Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/types.md Defines the startup configuration for libvips, controlling thread count, cache settings, and SIMD acceleration. Use this to customize libvips initialization via the Startup function. ```go type Config struct { ConcurrencyLevel int // Thread count (default: 1) MaxCacheFiles int // Max file cache entries MaxCacheMem int // Max memory cache in bytes MaxCacheSize int // Max cache size in entries ReportLeaks bool // Enable leak reporting CacheTrace bool // Enable cache tracing VectorEnabled bool // Enable SIMD acceleration VectorDisableTargets int64 // Mask of disabled SIMD targets } ``` -------------------------------- ### Get Image Height Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Retrieves the height of the image in pixels. Use this to understand the vertical dimension of the image. ```Go func (r *Image) Height() int ``` -------------------------------- ### Get Image Width Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Retrieves the width of the image in pixels. This is a fundamental property for image dimension analysis. ```Go func (r *Image) Width() int ``` ```Go w := image.Width() ``` -------------------------------- ### Shrink-on-Load vs. Load and Shrink Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Demonstrates efficient thumbnail loading by shrinking images during decoding compared to loading the full image and then shrinking. Use `NewThumbnailFile` for efficiency with large images. ```go // Efficient: shrinks while decoding thumb, _ := vips.NewThumbnailFile("huge.jpg", 200, nil) ``` ```go // Less efficient: loads full image then shrinks img, _ := vips.NewImageFromFile("huge.jpg", nil) img.Thumbnail(200, nil) ``` -------------------------------- ### Flood-fill operation on image Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Performs a flood-fill operation starting from coordinates (x, y) with the specified 'ink' color. ```go func (r *Image) DrawFlood(ink []float64, x, y int, options *DrawFloodOptions) error ``` -------------------------------- ### Creating Vipsgen Sources from Seekable and Non-Seekable Streams Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Demonstrates creating a Vipsgen source from a file (seekable) and an HTTP response body (non-seekable). Seekable streams allow for format-specific optimizations. ```go // Seekable (file, bytes.Buffer with seek capability) file, _ := os.Open("image.jpg") source := vips.NewSource(file) // Seeks if available // Non-seekable (network stream, pipe) resp, _ := http.Get("https://example.com/image.jpg") source := vips.NewSource(resp.Body) // Works but less efficient ``` -------------------------------- ### Config Structure Definition Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Defines the configuration options for libvips startup, including settings for concurrency, caching, and vector operations. ```go type Config struct { ConcurrencyLevel int MaxCacheFiles int MaxCacheMem int MaxCacheSize int ReportLeaks bool CacheTrace bool VectorEnabled bool VectorDisableTargets int64 } ``` -------------------------------- ### Get Animated Image Loop Count Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Returns the loop count for animated images. A value of 0 indicates infinite looping. ```Go func (r *Image) Loop() int ``` -------------------------------- ### Config Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/types.md Represents the startup configuration for libvips, allowing control over concurrency, caching, and performance features. ```APIDOC ## Config Startup configuration for libvips. ```go type Config struct { ConcurrencyLevel int // Thread count (default: 1) MaxCacheFiles int // Max file cache entries MaxCacheMem int // Max memory cache in bytes MaxCacheSize int // Max cache size in entries ReportLeaks bool // Enable leak reporting CacheTrace bool // Enable cache tracing VectorEnabled bool // Enable SIMD acceleration VectorDisableTargets int64 // Mask of disabled SIMD targets } ``` **Usage:** `Startup(config)` ``` -------------------------------- ### Get Animated Image Frame Delays Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Retrieves the per-frame delay in milliseconds for animated images. Handles potential errors during retrieval. ```Go func (r *Image) PageDelay() ([]int, error) ``` ```Go delays, err := image.PageDelay() if err != nil { log.Fatal(err) } for i, delay := range delays { fmt.Printf("Frame %d: %dms\n", i, delay) } ``` -------------------------------- ### Get Page Height Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Returns the height of a single page or frame in pixels. For multi-page images, this represents the height of each individual frame. ```Go func (r *Image) PageHeight() int ``` -------------------------------- ### HTTP Download, Thumbnail Creation, and Save Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Download an image from a URL, create a thumbnail using automatic shrink-on-load, and save it as a JPEG. This demonstrates processing network streams. ```go package main import ( "io" "log" "net/http" "github.com/cshum/vipsgen/vips" ) func main() { // Download image resp, err := http.Get("https://example.com/image.jpg") if err != nil { log.Fatal(err) } defer resp.Body.Close() // Create source from network stream source := vips.NewSource(resp.Body) defer source.Close() // Load with automatic shrink-on-load image, err := vips.NewThumbnailSource(source, 200, nil) if err != nil { log.Fatal(err) } defer image.Close() // Save thumbnail image.Jpegsave("thumb.jpg", &vips.JpegsaveOptions{Q: 90}) } ``` -------------------------------- ### Create Thumbnail from File Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Use NewThumbnailFile to create a thumbnail from a file, optimizing for size by shrinking during the load process. Specify the target width and optionally height and error handling behavior. ```go thumb, err := vips.NewThumbnailFile("large_photo.jpg", 200, &vips.ThumbnailFileOptions{ Height: 200, FailOn: vips.FailOnError, }) if err != nil { log.Fatal(err) } defer thumb.Close() ``` -------------------------------- ### Check Operation Availability Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md Before using a libvips operation, check if it is available using `vips.HasOperation`. This prevents errors when an operation is not compiled into the libvips installation. ```go // Check before using if vips.HasOperation("fftw") { // Use FFT } else { // Fallback } ``` -------------------------------- ### Get Image Color Space Interpretation Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Returns the color space interpretation (e.g., InterpretationSrgb, InterpretationLab). This is crucial for correct color rendering. ```Go func (r *Image) Interpretation() Interpretation ``` -------------------------------- ### Get Band Data Format Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Returns the data format of each band (e.g., BandFormatUchar, BandFormatFloat). This indicates the precision and type of pixel data. ```Go func (r *Image) BandFormat() BandFormat ``` -------------------------------- ### Configure libvips for Development/Testing Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Sets up libvips with a single concurrency level, a small cache memory limit, and enables leak reporting and cache tracing for debugging during development. ```go vips.Startup(&vips.Config{ ConcurrencyLevel: 1, MaxCacheMem: 10 * 1024 * 1024, // 10 MB ReportLeaks: true, CacheTrace: true, }) ``` -------------------------------- ### Get Image Bands Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Returns the number of bands (channels) in the image. This is useful for understanding color depth and type (e.g., RGB, RGBA). ```Go func (r *Image) Bands() int ``` -------------------------------- ### Vipsgen Source Error Handling Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Shows how to create a Vipsgen source and handle potential errors during its creation or when loading an image from it. Ensure the source is closed using defer. ```go source := vips.NewSource(file) if source == nil { // Failed to create source log.Fatal("Failed to create source") } deferr source.Close() image, err := vips.NewImageFromSource(source, nil) if err != nil { log.Fatal(err) // I/O or format error } ``` -------------------------------- ### Get ICC Profile Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/advanced-operations.md Retrieves the embedded ICC color profile from an image. Returns the profile data as bytes and a boolean indicating its presence. ```go func (r *Image) GetICCProfile() ([]byte, bool) ``` -------------------------------- ### Get Number of Pages/Frames Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Returns the total number of pages or frames in the image. For animated formats like GIF or WebP, this corresponds to the frame count. ```Go func (r *Image) Pages() int ``` -------------------------------- ### Go Wrapper for vipsgen_resize_with_options Source: https://github.com/cshum/vipsgen/blob/main/README.md This Go function provides a type-safe wrapper for the C `vipsgen_resize_with_options` function, managing optional parameters and CGO interactions. ```go // vipsgenResizeWithOptions vips_resize resize an image with optional arguments func vipsgenResizeWithOptions(in *C.VipsImage, scale float64, kernel Kernel, gap float64, vscale float64) (*C.VipsImage, error) { var out *C.VipsImage if err := C.vipsgen_resize_with_options(in, &out, C.double(scale), C.VipsKernel(kernel), C.double(gap), C.double(vscale)); err != 0 { return nil, handleImageError(out) } return out, nil } ``` -------------------------------- ### Get Image Coding Type Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Returns the coding type of the image data (e.g., CodingNone, CodingLabq). This can indicate compression or specific encoding schemes. ```Go func (r *Image) Coding() Coding ``` -------------------------------- ### Integrate Custom Reader with io.Seeker Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Demonstrates how to use a custom reader that implements io.ReadCloser and io.Seeker with Vipsgen. This allows for more control over input data streams, especially for operations requiring seeking. ```Go // Custom reader implementing io.ReadCloser type MyReader struct { data []byte pos int } func (r *MyReader) Read(p []byte) (int, error) { if r.pos >= len(r.data) { return 0, io.EOF } n := copy(p, r.data[r.pos:]) r.pos += n return n, nil } func (r *MyReader) Close() error { return nil } func (r *MyReader) Seek(offset int64, whence int) (int64, error) { var pos int64 switch whence { case io.SeekStart: pos = offset case io.SeekCurrent: pos = int64(r.pos) + offset case io.SeekEnd: pos = int64(len(r.data)) + offset } if pos < 0 || pos > int64(len(r.data)) { return 0, fmt.Errorf("invalid position") } r.pos = int(pos) return pos, nil } // Use custom reader func processCustom() error { reader := &MyReader{data: imageData} source := vips.NewSource(reader) defer source.Close() image, _ := vips.NewImageFromSource(source, nil) defer image.Close() // Process... } ``` -------------------------------- ### Proper vipsgen Application Shutdown Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Ensure proper initialization and shutdown of the vips library using Startup and Shutdown. Always defer Shutdown to guarantee cleanup, and explicitly close all images. ```go func main() { vips.Startup(&vips.Config{}) defer vips.Shutdown() // ... process images ... // Explicitly close all images for _, img := range images { img.Close() } } ``` -------------------------------- ### Get First Non-Alpha Channel Index Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/advanced-operations.md Use GetNonAlpha to find the index of the first channel that is not fully transparent (alpha). Returns an error if no such channel exists. ```go func (r *Image) GetNonAlpha() (int, error) ``` -------------------------------- ### Generating vipsgen Bindings Source: https://github.com/cshum/vipsgen/blob/main/README.md Generate Go bindings for libvips using the `vipsgen` command. Specify the output directory with the `-out` flag. ```bash vipsgen -out ./vips ``` -------------------------------- ### Handle Insufficient Memory Errors Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md For large images, use thumbnail with shrink-on-load, increase MaxCacheMem, or process in chunks to avoid 'out of memory' errors. ```go // 1. Use thumbnail with shrink-on-load for large images thumb, err := vips.NewThumbnailFile("huge_image.jpg", 200, nil) ``` ```go // 2. Increase available memory (if possible) vips.Startup(&vips.Config{ MaxCacheMem: 500 * 1024 * 1024, }) ``` ```go // 3. Process in chunks (for operations like crop) // Split large image processing into smaller regions ``` -------------------------------- ### Apply Gaussian Blur Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/advanced-operations.md Applies a Gaussian blur to an image. Use the Sigma parameter to control the blur radius. Moderate and strong blur examples are provided. ```go image.Blur(&vips.BlurOptions{ Sigma: 2.0, }) ``` ```go image.Blur(&vips.BlurOptions{ Sigma: 10.0, }) ``` -------------------------------- ### Thumbnail File Options Structure Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/types.md Options for creating thumbnails from files, focusing on height and failure conditions. ```go type ThumbnailFileOptions struct { Height int FailOn FailOn // ... other options } ``` -------------------------------- ### Load WebP from Source Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Loads a WebP image from a source stream. Use N: -1 to load all frames for animated WebP. ```go source := vips.NewSource(file) defersource.Close() image, err := vips.NewWebploadSource(source, &vips.WebploadSourceOptions{ N: -1, // All frames for animated WebP }) ``` -------------------------------- ### Create Thumbnail from Source Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Use NewThumbnailSource to create a thumbnail from a vips.Source, leveraging shrink-on-load for efficiency. This is suitable for loading images from custom data sources. ```go func NewThumbnailSource(source *Source, width int, options *ThumbnailSourceOptions) (*Image, error) ``` -------------------------------- ### Handle Permission Denied Errors Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md Use os.IsPermission to check for write permission issues and log a fatal error if the output file cannot be written. ```go err := image.Jpegsave(path, nil) if err != nil && os.IsPermission(err) { log.Fatalf("Cannot write to %s: %v", path, err) } ``` -------------------------------- ### Download and Resize Image from URL Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md This function downloads an image from a given URL, processes it by resizing, and saves it to a specified output path. It utilizes Vipsgen's streaming capabilities to handle network input. ```Go package main import ( "io" "log" "net/http" "os" "github.com/cshum/vipsgen/vips" ) func downloadAndResize(url string, outputPath string) error { // Download image from URL resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("HTTP %d", resp.StatusCode) } // Create source from network stream source := vips.NewSource(resp.Body) defer source.Close() // Load image image, err := vips.NewImageFromSource(source, nil) if err != nil { return err } defer image.Close() // Process image.Resize(0.5, nil) // Save to file return image.Jpegsave(outputPath, &vips.JpegsaveOptions{Q: 90}) ``` -------------------------------- ### Using Custom Generated Code Source: https://github.com/cshum/vipsgen/blob/main/README.md Import your custom-generated vips bindings into your Go project. Ensure the import path matches the output directory specified during generation. ```go package main import ( "yourproject/vips" ) ``` -------------------------------- ### Max/Min with Position Coordinates in Go Source: https://github.com/cshum/vipsgen/blob/main/examples/optional_outputs/README.md Get the coordinates of the maximum or minimum pixel values within an image using the Max or Min operations. This is useful for identifying extreme pixel locations. ```go maxOptions := vips.DefaultMaxOptions() maxValue, err := img.Max(maxOptions) // Access position of maximum value fmt.Printf("Maximum value: %.2f at position x=%d, y=%d\n", maxValue, maxOptions.X, maxOptions.Y) ``` -------------------------------- ### Enable CGO for vipsgen Build Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Ensure CGO is enabled when building the vipsgen library to link against libvips. This is a fundamental requirement for compilation. ```bash CGO_ENABLED=1 go build ``` -------------------------------- ### Create Source from io.ReadCloser Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Create a Source from any io.ReadCloser interface, such as a file. Ensure the underlying reader is closed after use. The Source itself must also be closed, ideally after image processing is complete. ```go file, err := os.Open("image.jpg") if err != nil { log.Fatal(err) } defer file.Close() source := vips.NewSource(file) defer source.Close() image, err := vips.NewImageFromSource(source, nil) if err != nil { log.Fatal(err) } defer image.Close() ``` -------------------------------- ### Configure libvips for Docker/Containers Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Sets up libvips for containerized environments with a limited concurrency level, a specific cache memory limit, a file cache limit, and optionally disables vector instructions if unsupported. ```go vips.Startup(&vips.Config{ ConcurrencyLevel: 2, MaxCacheMem: 50 * 1024 * 1024, // 50 MB MaxCacheFiles: 20, VectorEnabled: false, // Disable if unsupported in container }) ``` -------------------------------- ### Image Lifecycle Management Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/README.md Demonstrates the importance of explicitly closing Image objects to free underlying C memory. Always use 'defer image.Close()' after creating an image. ```go image, _ := vips.NewImageFromFile("photo.jpg", nil) defer image.Close() // Always close! ``` -------------------------------- ### Ensure Image Resource Cleanup Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md Use `defer image.Close()` immediately after successfully creating an image to guarantee that resources are released, even if subsequent operations result in an error. ```go image, err := vips.NewImageFromFile(path, nil) if err != nil { return err } defer image.Close() // Always close, even on error ``` -------------------------------- ### Enable Vector (SIMD) Acceleration Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Enable SIMD (SSE, AVX) acceleration if libvips was compiled with vector support. This can significantly speed up image processing on compatible hardware. ```go Config{ VectorEnabled: true, } ``` -------------------------------- ### vipsgen Command Line Options Source: https://github.com/cshum/vipsgen/blob/main/README.md View available command-line options for the `vipsgen` tool. Use flags like `-debug`, `-extract`, `-out`, etc., to customize the generation process. ```bash Usage of vipsgen: -debug Enable debug json output -extract Extract embedded templates to a directory -extract-dir string Directory to extract templates to (default "./templates") -include-test Include test files in generated output -out string Output directory (default "./vips") -templates string Template directory (uses embedded templates if not specified) ``` -------------------------------- ### Generate Thumbnail from URL with Shrink-on-Load Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Efficiently generate a thumbnail from a remote URL by leveraging shrink-on-load capabilities. This method downloads the image, creates a thumbnail source, and saves the result with specified quality. ```go func generateThumbnail(inputURL, outputPath string, width int) error { // Download with automatic shrink-on-load resp, err := http.Get(inputURL) if err != nil { return err } defer resp.Body.Close() source := vips.NewSource(resp.Body) defer source.Close() // Load with shrink-on-load (very efficient for large images) thumb, err := vips.NewThumbnailSource(source, width, &vips.ThumbnailSourceOptions{ Height: width, FailOn: vips.FailOnError, }) if err != nil { return err } defer thumb.Close() // Save thumbnail return thumb.Jpegsave(outputPath, &vips.JpegsaveOptions{Q: 85}) } ``` -------------------------------- ### Create White Image Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Use NewWhite to create a white image of specified dimensions and options. ```go func NewWhite(width, height int, options *WhiteOptions) (*Image, error) ``` -------------------------------- ### C Wrapper for vips_resize (Required Args) Source: https://github.com/cshum/vipsgen/blob/main/README.md This C function wraps `vips_resize` to accept only the required arguments, directly calling the libvips function. ```c int vipsgen_resize(VipsImage* in, VipsImage** out, double scale) { return vips_resize(in, out, scale, NULL); } ``` -------------------------------- ### Load Animated GIF from Source Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Loads an animated GIF from a source stream. Use N: -1 to load all frames. ```go source := vips.NewSource(file) defersource.Close() // Load all frames image, err := vips.NewGifloadSource(source, &vips.GifloadSourceOptions{ N: -1, // All frames }) ``` -------------------------------- ### General Remapping with Lookup Tables Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Perform general remapping of image pixels using one or more lookup tables (Images). ```go func (r *Image) Remap(index []*Image, options *RemapOptions) error ``` -------------------------------- ### Loading Animated GIF Frames Source: https://github.com/cshum/vipsgen/blob/main/README.md Use `NewGifload` to load animated GIFs. Set `N` to -1 to load all frames. ```go image, err := vips.NewGifload("animation.gif", &vips.GifloadOptions{ N: -1, // -1 = load all frames }) ``` -------------------------------- ### Build Lookup Table Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Build a lookup table for image processing operations. This function does not take any arguments. ```go func (r *Image) Buildlut() error ``` -------------------------------- ### Handle Unsupported Image Format Errors Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md Check for format support before attempting to load an image to prevent 'unsupported image format' errors. ```go image, err := vips.NewImageFromFile("image.xyz", nil) if err != nil { if strings.Contains(err.Error(), "unsupported") { log.Println("Format not supported, try converting first") } } ``` -------------------------------- ### Configure libvips for Web Services Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/configuration.md Optimizes libvips for web services on a single machine by setting a moderate concurrency level, a larger cache memory limit, a file cache limit, and enabling vector instructions. ```go vips.Startup(&vips.Config{ ConcurrencyLevel: 4, MaxCacheMem: 100 * 1024 * 1024, // 100 MB MaxCacheFiles: 50, VectorEnabled: true, }) ``` -------------------------------- ### Load TIFF from Source Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md Loads a TIFF image from a source stream. Use N: -1 to load all pages. ```go source := vips.NewSource(file) defersource.Close() image, err := vips.NewTiffloadSource(source, &vips.TiffloadSourceOptions{ N: -1, // All pages }) ``` -------------------------------- ### Define ResizeOptions for vips_resize Source: https://github.com/cshum/vipsgen/blob/main/README.md Defines an options struct for the vips_resize function, including resampling kernel, gap, and vertical scale. Use this struct to pass optional arguments to the Resize method. ```go // ResizeOptions optional arguments for vips_resize type ResizeOptions struct { // Kernel Resampling kernel Kernel Kernel // Gap Reducing gap Gap float64 // Vscale Vertical scale image by this factor Vscale float64 } ``` -------------------------------- ### Load Image from File Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Use NewImageFromFile to load an image from a file path. It automatically detects the image format. Ensure to close the image when done. ```go image, err := vips.NewImageFromFile("photo.jpg", nil) if err != nil { log.Fatal(err) } deffer image.Close() ``` -------------------------------- ### PNG Load Options Structure Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/types.md Standard load options for PNG images. ```go type PngloadOptions struct { Memory bool Access Access FailOn FailOn Revalidate bool } ``` -------------------------------- ### JPEG Save Operation with Options Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/INDEX.md Shows how to save an image in JPEG format with specific quality settings using the Jpegsave method and its options struct. Error handling is included. ```go err := image.Jpegsave("output.jpg", &vips.JpegsaveOptions{Q: 90}) if err != nil { return err } ``` -------------------------------- ### Create Spatial Frequency Response Visualization Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/advanced-operations.md Use NewEye to generate a visualization of the spatial frequency response. Requires width, height, and eye options. ```go func NewEye(width, height int, options *EyeOptions) (*Image, error) ``` -------------------------------- ### Source Structure for Input Stream Wrapper Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/types.md Wraps an io.ReadCloser and io.Seeker to provide an input stream for reading image data. Use NewSource to create and Close to release resources. ```go type Source struct { reader io.ReadCloser seeker io.Seeker // ... internal fields } ``` ```go file, _ := os.Open("image.jpg") defer file.Close() source := vips.NewSource(file) deffer source.Close() image, _ := vips.NewImageFromSource(source, nil) ``` -------------------------------- ### Join Images as Bands Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Use NewBandjoin to join multiple images together as bands. Accepts a slice of images. ```go func NewBandjoin(in []*Image) (*Image, error) ``` -------------------------------- ### Log Errors Appropriately Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md Log errors using `log.Printf` for warnings that allow the program to continue, or `log.Fatalf` for critical errors that should terminate the program. ```go if err != nil { log.Printf("Warning: %s (continuing)", err) // or log.Fatalf("Fatal: %s", err) } ``` -------------------------------- ### Build Image Histogram Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Construct a histogram for the image. Options can be provided to customize the histogram generation. ```go func (r *Image) Hist(options *HistOptions) error ``` -------------------------------- ### Implement Image Resize Method Source: https://github.com/cshum/vipsgen/blob/main/README.md Encapsulates the vips_resize functionality within an idiomatic Go method on the *Image struct. It handles both basic and options-based resizing, managing potential errors and updating the image. ```go // Resize vips_resize resize an image func (r *Image) Resize(scale float64, options *ResizeOptions) error { if options != nil { // Use the WithOptions variant when options are provided out, err := vipsgenResizeWithOptions(r.image, scale, options.Kernel, options.Gap, options.Vscale) if err != nil { return err } r.setImage(out) return nil } // Use the basic variant for required parameters only out, err := vipsgenResize(r.image, scale) if err != nil { return err } r.setImage(out) return nil } ``` -------------------------------- ### Handle File Not Found Errors Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md Use os.IsNotExist to specifically catch and handle 'unable to open file' errors when a file path is invalid or inaccessible. ```go image, err := vips.NewImageFromFile(path, nil) if err != nil { if os.IsNotExist(err) { log.Fatalf("File not found: %s", path) } } ``` -------------------------------- ### Image Lifetime Management Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/INDEX.md Illustrates the importance of explicitly closing an image resource after use to manage its lifetime. The defer keyword ensures closure. ```go image, _ := vips.NewImageFromFile("photo.jpg", nil) defer image.Close() ``` -------------------------------- ### Source Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/types.md A wrapper for input streams to read image data, supporting io.ReadCloser and io.Seeker interfaces. ```APIDOC ## Source Input stream wrapper for reading image data. ```go type Source struct { reader io.ReadCloser seeker io.Seeker // ... internal fields } ``` **Methods:** - `NewSource(reader io.ReadCloser) *Source` — Create from io.ReadCloser - `Close()` — Close the source **Example:** ```go file, _ := os.Open("image.jpg") deffer file.Close() source := vips.NewSource(file) defer source.Close() image, _ := vips.NewImageFromSource(source, nil) ``` ``` -------------------------------- ### C Wrapper for vips_resize (Optional Args) Source: https://github.com/cshum/vipsgen/blob/main/README.md This C function wraps `vips_resize` to handle optional parameters using `VipsOperation`. It includes type-specific setters and operation execution. ```c int vipsgen_resize_with_options(VipsImage* in, VipsImage** out, double scale, VipsKernel kernel, double gap, double vscale) { VipsOperation *operation = vips_operation_new("resize"); if (!operation) return 1; if ( vips_object_set(VIPS_OBJECT(operation), "in", in, NULL) || vips_object_set(VIPS_OBJECT(operation), "scale", scale, NULL) || vipsgen_set_int(operation, "kernel", kernel) || vipsgen_set_double(operation, "gap", gap) || vipsgen_set_double(operation, "vscale", vscale) ) { g_object_unref(operation); return 1; } int result = vipsgen_operation_execute(operation, "out", out, NULL); return result; } ``` -------------------------------- ### Load Image from Source (Seekable/Non-Seekable) Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/streaming.md This method works with both seekable and non-seekable streams. Use this for general image loading. ```go // Works with both seekable and non-seekable image, _ := vips.NewImageFromSource(source, nil) ``` -------------------------------- ### Go Wrapper for vipsgen_resize Source: https://github.com/cshum/vipsgen/blob/main/README.md This Go function provides a type-safe wrapper for the C `vipsgen_resize` function, handling CGO calls and error management. ```go // vipsgenResize vips_resize resize an image func vipsgenResize(in *C.VipsImage, scale float64) (*C.VipsImage, error) { var out *C.VipsImage if err := C.vipsgen_resize(in, &out, C.double(scale)); err != 0 { return nil, handleImageError(out) } return out, nil } ``` -------------------------------- ### Create Black Image Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Use NewBlack to create a black image of specified dimensions and options. ```go func NewBlack(width, height int, options *BlackOptions) (*Image, error) ``` -------------------------------- ### Handle Unsupported Write Format Errors Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/errors.md If libvips does not support writing to the requested format, convert the image to a supported format like JPEG before saving. ```go err := image.Jpegsave("output.xyz", nil) if err != nil && strings.Contains(err.Error(), "no write") { // Convert to supported format image.Jpegsave("output.jpg", nil) } ``` -------------------------------- ### NewThumbnailFile Source: https://github.com/cshum/vipsgen/blob/main/_autodocs/api-reference/image.md Create a thumbnail from a file with shrink-on-load optimization. This function allows precise control over thumbnail dimensions and error handling. ```APIDOC ## NewThumbnailFile ### Description Create a thumbnail from a file with shrink-on-load optimization. ### Method `NewThumbnailFile(filename string, width int, options *ThumbnailFileOptions) (*Image, error)` ### Parameters #### Path Parameters - **filename** (string) - Required - Path to image file - **width** (int) - Required - Target width in pixels - **options** (*ThumbnailFileOptions) - Optional - Thumbnail options ### Request Example ```go thumb, err := vips.NewThumbnailFile("large_photo.jpg", 200, &vips.ThumbnailFileOptions{ Height: 200, FailOn: vips.FailOnError, }) if err != nil { log.Fatal(err) } defer thumb.Close() ``` ### Response #### Success Response (*Image) Returns an Image object representing the thumbnail. #### Error Response (error) Returns an error if the thumbnail creation fails. ```