Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Vips Laravel Package

jcupitt/vips

PHP FFI bindings for libvips (8.7+) on PHP 7.4+. Build fast, low-memory image processing pipelines and stream operations in parallel. Great for thumbnails, transforms, and saving to many formats with libvips speed.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install libvips system library**:
   ```bash
   # Debian/Ubuntu
   sudo apt-get install --no-install-recommends libvips42

   # macOS (Homebrew)
   brew install vips

   # Windows: Download from [libvips.org](https://www.libvips.org/install.html)
  1. Enable PHP FFI in php.ini:

    ffi.enable=1
    zend.max_allowed_stack_size=-1  # Required for PHP 8.3+
    
  2. Install via Composer:

    composer require jcupitt/vips
    
  3. Verify installation:

    use Jcupitt\Vips;
    echo Vips\Config::version(); // Should print libvips version (e.g., "8.18.0")
    

First Use Case: Thumbnail Generation

use Jcupitt\Vips;

// Load image
$image = Vips\Image::newFromFile('input.jpg');

// Create thumbnail (128px width, auto-height)
$thumbnail = $image->thumbnail(128);

// Save result
$thumbnail->writeToFile('thumbnail.jpg');

Where to Look First

  • API Docs – Auto-generated reference for all methods.
  • examples/ directory – Practical use cases (e.g., animate-image.php, keep.php).
  • Libvips Official Docshttps://libvips.org/API/current for advanced operations.

Implementation Patterns

1. Pipeline Pattern (Immutable Operations)

Libvips follows a functional pipeline model where operations return new images without modifying the original. Chain operations for efficiency:

$processed = $image
    ->resize(0.5)          // Half size
    ->sharpen(1.0)         // Sharpen
    ->jpegsave('output.jpg', ['Q' => 85]); // Save with 85% quality

2. Memory Efficiency with Streaming

Use streaming operations to avoid loading entire images into memory:

// Stream from file to file (no full image in memory)
$image = Vips\Image::newFromFile('large.tif');
$image->writeToFile('compressed.jpg', ['Q' => 70]);

Key Methods:

  • newFromFile() – Load from disk.
  • writeToFile() – Save to disk (supports formats like JPEG, PNG, TIFF).
  • writeToMemory() – Return raw image data as a string.

3. Batch Processing

Process multiple images efficiently using libvips' parallel pipelines:

$images = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
foreach ($images as $file) {
    $img = Vips\Image::newFromFile($file);
    $processed = $img->resize(0.7)->jpegsave("processed/{$file}");
}

Tip: Use Vips\Image::newFromBuffer() for in-memory processing:

$buffer = file_get_contents('image.jpg');
$img = Vips\Image::newFromBuffer($buffer);

4. Custom Operations with composite

Combine images using blend modes (e.g., overlay, multiply):

$base = Vips\Image::newFromFile('background.jpg');
$overlay = Vips\Image::newFromFile('logo.png');

// Composite with "overlay" blend mode
$composite = $base->composite($overlay, Vips\BlendMode::OVERLAY);
$composite->writeToFile('result.jpg');

Blend Modes: OVERLAY, MULTIPLY, SCREEN, DARKEN, LIGHTEN, etc.


5. Progress Tracking

Monitor long-running operations:

$image = Vips\Image::newFromFile('huge.tif');
$image->setProgress(function ($progress) {
    echo "Progress: " . round($progress * 100) . "%\n";
});
$image->resize(0.5)->writeToFile('small.tif');

6. Error Handling

Wrap operations in try-catch to handle libvips errors:

try {
    $image = Vips\Image::newFromFile('corrupt.jpg');
} catch (Vips\Exception $e) {
    logError("Failed to load image: " . $e->getMessage());
}

Gotchas and Tips

1. Performance Pitfalls

  • Avoid intermediate variables: Libvips optimizes pipelines when chained:
    // ❌ Less efficient (creates temporary image)
    $temp = $image->resize(0.5);
    $result = $temp->sharpen(1.0);
    
    // ✅ More efficient (pipeline)
    $result = $image->resize(0.5)->sharpen(1.0);
    
  • Use keep() for debugging: Prevents garbage collection of intermediate images:
    $debugImg = $image->resize(0.5)->keep();
    

2. Memory Management

  • Libvips is memory-efficient, but large images still require RAM:
    • For >1GB images, use streaming (writeToFile directly).
    • 32-bit systems: Libvips may fail on very large images (use 64-bit PHP).
  • Disable FFI stack checks (PHP 8.3+):
    zend.max_allowed_stack_size=-1  # Required in php.ini
    

3. Common Errors & Fixes

Error Cause Solution
Failed to load libvips Missing system library Install libvips (apt-get install libvips42)
FFI extension not enabled PHP FFI disabled Enable in php.ini (ffi.enable=1)
Stack overflow (PHP 8.3+) FFI callback conflicts Set zend.max_allowed_stack_size=-1
Unsupported format Missing libvips plugins Install full libvips (apt-get install libvips-tools)
Permission denied File access issues Check open_basedir in php.ini

4. Debugging Tips

  • Check libvips version:
    echo Vips\Config::version(); // Should match system libvips
    
  • Enable logging:
    Vips\Image::setLogging(new \Monolog\Logger('vips'));
    
  • Inspect image metadata:
    $image = Vips\Image::newFromFile('test.jpg');
    print_r($image->getFields()); // Lists all available fields
    

5. Cross-Platform Quirks

  • Windows:
    • Add library path explicitly:
      Vips\FFI::addLibraryPath("C:/vips-dev-8.16/bin");
      
    • Use full paths for file operations (e.g., C:\path\to\image.jpg).
  • Docker:
    • Install libvips in the container:
      RUN apt-get install -y libvips42
      
  • macOS:
    • Use brew install vips and ensure PHP FFI is enabled.

6. Extending Libvips

  • Add custom operations: Libvips supports arbitrary operations via FFI. Example: Call a custom C function (advanced):
    $ffi = FFI::cdef("
        int custom_operation(double *data, int width, int height);
    ", "libcustom.so");
    $result = $ffi->custom_operation($image->getData(), $image->width, $image->height);
    
  • Wrap in a service class:
    class ImageProcessor {
        public function optimize(Jcupitt\Vips\Image $image, int $quality): string {
            return $image
                ->resize(0.8)
                ->jpegsave(null, ['Q' => $quality])
                ->writeToMemory();
        }
    }
    

7. Configuration Quirks

  • FFI Library Path:
    • On Linux, libvips is usually in /usr/lib/x86_64-linux-gnu/.
    • On macOS, it’s /usr/local/lib/libvips.dylib.
    • Override with Vips\FFI::addLibraryPath().
  • PHP 8.4+:
    • Some methods may require type hints. Check the changelog for fixes.

8. Security Considerations

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle