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

Imagine Svg Laravel Package

contao/imagine-svg

Imagine-compatible SVG image library for PHP/Contao. Open, crop, resize, and apply common effects (gamma, grayscale, blur, etc.) to SVGs and save results. Includes SVG-aware sizing via SvgBox for absolute, aspect-ratio, or undefined dimensions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require contao/imagine-svg
    

    Require the Imagine\Gd\Imagine or Imagine\Imagick\Imagine service (if using GD/Gmagick) and register the SVG driver:

    use Imagine\Gd\Imagine;
    use Imagine\Imagick\Imagine;
    use Contao\ImagineSvg\ImagineSvg;
    
    $imagine = new Imagine();
    $imagine->registerDriver('svg', new ImagineSvg());
    
  2. First Use Case Convert an SVG to PNG with improved namespace handling:

    $image = $imagine->open('path/to/image.svg');
    $image->save('path/to/output.png');
    
  3. Where to Look First

    • GitHub Repository
    • src/ImagineSvg.php (core logic, updated for XML namespaces)
    • tests/ (updated test cases for edge cases like invalid resize filters)

Implementation Patterns

Common Workflows

  1. Dynamic SVG Processing with Resilience Handle edge cases like invalid resize filters gracefully:

    $image = $imagine->open('path/to/image.svg');
    $image->resize(new \Imagine\Image\Box(200, 200)); // No exception thrown for invalid filters
    $image->save('path/to/output.png');
    
  2. Namespace-Aware SVG Handling Process SVGs with XML namespaces (e.g., <svg xmlns="http://www.w3.org/2000/svg">):

    $svgWithNamespaces = <<<SVG
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="40" fill="red"/>
    </svg>
    SVG;
    $image = $imagine->openFromString($svgWithNamespaces);
    $image->save('output.png');
    
  3. Integration with Laravel Filesystem Leverage Laravel’s Storage facade for cloud-optimized SVG handling:

    use Illuminate\Support\Facades\Storage;
    
    $svgContent = Storage::disk('s3')->get('logos/brand.svg');
    $image = $imagine->openFromString($svgContent)
        ->resize(new \Imagine\Image\Box(120, 120))
        ->save('optimized-logo.png');
    
  4. Batch Processing with Error Handling Process multiple SVGs while gracefully handling invalid resize filters:

    $svgFiles = Storage::disk('public')->files('svgs');
    foreach ($svgFiles as $file) {
        try {
            $image = $imagine->open(storage_path("app/{$file}"))
                ->resize(new \Imagine\Image\Box(300, 300))
                ->save("public/thumbs/{$file}.png");
        } catch (\Exception $e) {
            Log::warning("Failed to process {$file}: {$e->getMessage()}");
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Dependency Conflicts

    • Ensure imagine/imagine (v1.x) is installed and compatible. Avoid v2.x (breaking changes).
    • If using Gmagick, ensure the PHP extension is installed (pecl install gmagick).
  2. Invalid Resize Filters

    • New in 1.0.4: No longer throws exceptions for invalid resize filters (e.g., negative dimensions). Log warnings instead:
      $image->resize(new \Imagine\Image\Box(-100, 200)); // Silently ignored
      
  3. XML Namespaces in SVGs

    • New in 1.0.4: Properly handles SVGs with XML namespaces (e.g., <svg xmlns="...">). Previously, this could cause parsing errors.
    • Test with complex SVGs:
      $image = $imagine->open('path/to/complex.svg'); // Now works with namespaces
      
  4. Performance Bottlenecks

    • SVG-to-PNG conversion is CPU-intensive. Offload to a queue (Laravel Queues) for large files:
      dispatch(new ConvertSvgJob($svgPath, $pngPath));
      

Debugging Tips

  • Log Errors: Wrap conversions in try-catch blocks to log failures (especially for invalid resize filters):
    try {
        $image->resize(new \Imagine\Image\Box(0, 0)); // Edge case
        $image->save($outputPath);
    } catch (\Exception $e) {
        Log::error("Conversion failed: {$e->getMessage()}");
    }
    
  • Validate SVGs: Use an online validator (e.g., SVGOMG) to pre-check files, especially those with namespaces.

Extension Points

  1. Custom Filters with Fallback Logic Extend the driver to handle invalid resize filters explicitly:

    class CustomImagineSvg extends ImagineSvg {
        public function resize($size) {
            if ($size->getWidth() <= 0 || $size->getHeight() <= 0) {
                Log::warning("Invalid resize dimensions: {$size->getWidth()}x{$size->getHeight()}");
                return $this; // Skip resize
            }
            return parent::resize($size);
        }
    }
    
  2. Namespace-Aware Preprocessing Strip or modify namespaces before processing:

    class NamespaceAwareImagineSvg extends ImagineSvg {
        public function open($file) {
            $content = file_get_contents($file);
            $content = $this->normalizeNamespaces($content); // Custom logic
            return parent::openFromString($content);
        }
    }
    
  3. Laravel Service Provider Register the driver globally in AppServiceProvider:

    public function register() {
        $this->app->singleton('imagine.svg', function () {
            return new ImagineSvg(); // Now handles namespaces and invalid filters
        });
    }
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor