Download the PHP package genaker/imageaibundle without Composer

On this page you can find all versions of the php package genaker/imageaibundle. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package imageaibundle

Genaker ImageAIBundle - Magento 2 Module

Magento 2 module for intelligent image resizing with caching and AI-powered image modification support. This module provides on-the-fly image resizing with support for multiple formats, quality control, and optional AI-powered image enhancement using Google Gemini API.

Features

Installation

Via Composer (Recommended)

Note: During installation, a test image (wt09-white_main_1.jpg) will be automatically copied to /pub/media/catalog/product/w/t/ for testing purposes. You can use this image to test all resize functionality.

Manual Installation

  1. Copy the module to app/code/Genaker/ImageAIBundle
  2. Run the following commands:

Note: The test image will be automatically installed to /pub/media/catalog/product/w/t/wt09-white_main_1.jpg during setup:upgrade.

Configuration

Navigate to Stores > Configuration > Genaker > Image AI Resize to configure:

General Settings

Default Limits

Usage

Frontend URL Format

Basic Resize (Short Format - Recommended)

Example:

Legacy Format (Still Supported)

Example:

With Signature (if enabled)

URL Format Options: Base64 vs Regular

The module supports two URL formats for image resizing, both optimized for nginx caching:

Regular URL Format (Query String)

Format:

Example:

Characteristics:

Base64 URL Format (Recommended for Production)

Format:

Example:

How it works:

Benefits:

Decoding Example: The base64 string aXAvY2F0YWxvZy9wcm9kdWN0L3cvdC93dDA5LXdoaXRlX21haW5fMS5qcGc_Zj1qcGVnJmg9NDAwJnc9NDAw decodes to:

Both formats use the same cache:

Nginx Configuration

The module is designed to work with default nginx configuration without requiring custom rules. Here's how it works:

Default Nginx Behavior

With standard Magento nginx configuration, requests to /media/resize/ are handled as follows:

  1. Cache Hit: If the cache file exists at /pub/media/resize/{base64}.{ext}, nginx serves it directly (no PHP)
  2. Cache Miss: If the file doesn't exist, nginx falls back to /get.php which routes to PHP
  3. PHP Processing: PHP generates the resized image and saves it to the cache path
  4. Subsequent Requests: Future requests are served directly by nginx from cache

Cache Path Structure

Cache files are stored using base64-encoded filenames:

Example cache file:

Why base64 encoding?

Nginx Configuration (No Changes Required)

The module works with Magento's default nginx configuration. The standard try_files directive handles everything:

How it works:

  1. First, nginx checks if $uri exists (cache file)
  2. If not found, checks if $uri/ is a directory (shouldn't match due to base64 format)
  3. Finally, falls back to /get.php which routes to PHP via the Media plugin

Cache File Permissions

Ensure nginx has write access to the cache directory:

Performance Benefits

Manual Browser Testing

You can test the image resize functionality directly in your browser by constructing URLs with the appropriate parameters.

URL Structure

The module supports two URL formats:

1. Regular URL Format (Query String):

2. Base64 URL Format (Recommended for Production):

Legacy format (still supported for backward compatibility):

Note:

Constructing Test URLs

1. Basic Image Resize (Width & Height)

Using the test image included with the module:

Regular URL format:

Base64 URL format (same result, better caching):

2. Resize with Quality Control

Regular URL format:

Base64 URL format:

3. Width Only (Height auto-scales)

Regular URL format:

Base64 URL format:

4. Height Only (Width auto-scales)

Regular URL format:

Base64 URL format:

5. Format Conversion (JPEG to WebP)

Regular URL format:

Base64 URL format:

6. Format Conversion (JPEG to PNG)

Regular URL format:

Base64 URL format:

Note: Both URL formats generate the same cache file and return identical results. Use base64 format for production (better nginx caching) and regular format for development/testing (easier to read and construct).

7. With Signature (if signature validation is enabled)

8. Testing Gemini AI Integration (Admin Only)

To test AI-powered image modification, you need to:

Note: The module includes a test image (wt09-white_main_1.jpg) that is automatically copied to /pub/media/catalog/product/w/t/ during installation. You can use this image for testing all resize functionality.

Note: The prompt parameter is only available for admin users or when signature validation is enabled (signature provides security).

URL Parameter Encoding

When constructing URLs manually, ensure proper URL encoding:

Testing Checklist

  1. Basic Resize: Test with width and height parameters
  2. Format Conversion: Test converting between JPEG, PNG, WebP, GIF
  3. Quality Control: Test different quality values (1-100)
  4. Caching: Request the same URL twice - second request should be faster (cache hit)
  5. Error Handling: Test with invalid parameters or non-existent images
  6. Gemini AI: Test AI modification with appropriate prompts (admin only)

Example Test Scenarios

Scenario 1: Resize Product Image

Scenario 2: Create Thumbnail

Scenario 3: Optimize for Web

Troubleshooting Browser Testing

URL Parameters

Parameter Description Required Example
w Width in pixels No 300
h Height in pixels No 300
q Quality (0-100) No 85
f Format (webp, jpg, jpeg, png, gif) Yes webp
a Aspect ratio (inset, outbound) No inset
sig Signature (if validation enabled) Yes* abc123...
prompt AI modification prompt (admin only) No enhance colors
video Enable video generation (Veo 3.1) No true
aspectRatio Video aspect ratio (16:9, 9:16, 1:1) No 16:9
poll Wait for video completion (synchronous) No true
operation Operation ID for polling video status No operations/...
silentVideo Generate silent video (no audio) to avoid audio-related safety filters No true
return Return format: video to return video content directly instead of JSON No video

* Required only if signature validation is enabled

Video Generation

Video Model Selection (Environment Variables)

The module supports two video generation models that can be selected via environment variables:

Default: Veo 3.1 (Google AI Studio)

Alternative: Imagen (Vertex AI) - For Testing

Environment Variables:

Model Comparison:

Feature Veo 3.1 Imagen
Quality High Good
Speed Slower Faster
Quotas Standard Higher
Use Case Production Testing
Endpoint Google AI Studio Vertex AI

Note: When VIDEO_MODEL=imagen is set but VERTEX_AI_ENDPOINT is not configured, the module will fall back to Veo 3.1 and log a warning.

Video Generation Examples

Video generation uses the same URL structure as image resizing, but with the video=true parameter. The endpoint returns JSON responses instead of image files.

Base URL Format:

Basic Video Generation (Async Mode)

Start video generation (returns operation ID for polling):

Response (JSON):

Poll for completion:

Synchronous Video Generation

Wait for video completion (may take 30-60 seconds):

Response (JSON):

Video Generation with Different Aspect Ratios

16:9 (Landscape):

9:16 (Portrait):

1:1 (Square):

Video Generation Examples

Example 1: Transform Product Image to Summer Scene

Example 2: Create Animated Product Showcase

Example 3: Generate Silent Video (No Audio)

Example 4: Return Video Content Directly (Not JSON)

This returns the actual video file content (MP4) that browsers can play directly, instead of JSON response.

Example 5: Video Caching Videos are automatically cached based on image path, prompt, and aspect ratio. Same parameters = same cached video:

Video Generation Notes

Troubleshooting Video Generation

Error: "Video generation service is not available"

Error: "Gemini API error (403)"

Error: "Video generation timeout"

Error: "Video generation was blocked by safety filters"

Error: "Video generation error (Code: 13)"

Error: "Failed to download video from URI (Status: 302)"

Error: "No video found in API response"

Note: The module uses direct HTTP calls to Gemini API, so no SDK updates are required. Video generation works as long as your API key has Veo 3.1 access.

Admin URL Generator

AI Image Generation Prompt Examples

This section provides examples of effective prompts for AI-powered image generation and modification using Google Gemini. These prompts are language-agnostic and can be used with any implementation that supports Gemini's image generation capabilities.

Text-to-Image Generation

Photorealistic Portrait:

Cartoon Style:

Image Editing and Modification

Outfit Change:

Simple Modification:

Product Photography Enhancement

Studio Product Photo:

Logo Design and Application

Logo Creation:

Logo Application:

Fashion and Product Composition

Fashion Lookbook:

Prompt Engineering Tips

Python Implementation for Video Generation

The module includes a Python-based alternative implementation for video generation that offers enhanced performance, better error handling, and improved reliability for production environments.

Overview

The Python implementation (pygento/agento_video.py) provides a standalone script that can be used independently or via Magento CLI proxy command (agento-p:video). It uses Google's Generative AI SDK and Python's requests library for robust API interactions.

Benefits of Python Implementation

  1. Better Performance: Python's requests library handles large binary streams (video files) more efficiently than PHP cURL for long-running downloads
  2. Automatic Redirect Handling: Python's requests library automatically follows HTTP redirects (302), eliminating the need for manual redirect configuration
  3. Decoupled Processing: Can run as a standalone background worker without taxing PHP-FPM processes
  4. Better Error Handling: More detailed error messages and safety filter detection
  5. Multiple Image Processing: Process multiple images with the same prompt in a single command
  6. Robust MIME Detection: Uses Python's built-in mimetypes library for accurate MIME type detection
  7. Scalability: Can be easily wrapped in a Docker container or deployed as a separate microservice
  8. Cross-Platform: Works on Linux, macOS, and Windows with Python 3.7+

Installation

Install Python dependencies:

Or install manually:

Usage via Magento CLI (Recommended)

The easiest way to use the Python implementation is through the Magento CLI proxy command:

Basic Usage

Multiple Images

With All Options

Note: The --base-url parameter is automatically retrieved from Magento's store configuration, so you don't need to specify it manually.

Usage as Standalone Python Script

You can also run the Python script directly:

Command Options

Option Description Required
--image-path or -ip Path(s) to source image(s) (can specify multiple) Yes
--prompt or -p Video generation prompt Yes
--aspect-ratio or -ar Aspect ratio (16:9, 9:16, 1:1) No (default: 16:9)
--silent-video or -sv Generate silent video (avoids audio safety filters) No
--poll Wait for video completion (synchronous mode) No
--api-key Google Gemini API key (or set GEMINI_API_KEY env var) No
--base-path Magento base path (auto-detected when using Magento CLI) No
--base-url Base URL for video URLs (auto-detected from Magento config) No

Output Format

The Python implementation always returns JSON (unlike the PHP command which supports multiple formats):

Key Features

When to Use Python Implementation

Use Python implementation when:

Use PHP implementation when:

Integration with Magento

The Python implementation integrates seamlessly with Magento:

  1. Automatic Base URL: Magento CLI command automatically retrieves base URL from store configuration
  2. Shared Cache: Uses the same cache directory (pub/media/video/) as PHP implementation
  3. Consistent Output: Returns the same JSON structure as PHP implementation
  4. Same API: Uses the same Gemini Veo 3.1 API endpoints

Example: Batch Processing

Process multiple product images in a single command:

This will generate videos for all three images and return a summary with individual results.

Troubleshooting Python Implementation

Python Not Found:

Module Not Found Errors:

Permission Errors:

API Key Issues:

For more details, see the Python-specific README.

Navigate to Genaker > Image Resize > Generate to generate resize URLs with signature validation.

API Usage

Service Interface

Cache Management

Image Cache

Resized images are automatically cached in /pub/media/cache/resize/ directory. The cache structure follows the image path structure for easy management.

Clearing Image Cache:

Video Cache

Generated videos are automatically cached in /pub/media/video/ directory. Videos are cached based on:

Cache key format: md5(imagePath|prompt|aspectRatio)

Video Cache Behavior:

Clearing Video Cache:

Or use Magento cache management:

Note: Video cache is separate from image cache and is always enabled for optimal performance.

Security

Signature Validation

When signature validation is enabled, all resize URLs must include a valid signature parameter. This prevents unauthorized image resizing and protects against abuse.

Generating Signatures:

The signature is calculated as:

Where:

Programmatic URL Generation

The module provides multiple ways to generate image resize URLs programmatically:

1. Using ResizeUrlGenerationService (Recommended)

The ResizeUrlGenerationService is the core service for generating resize URLs. It's registered in Magento's dependency injection container and can be injected into any class.

In PHP Classes (Blocks, Controllers, etc.):

Service Methods:

2. Using Helper Class (Global Access)

The ImageResizeUrl helper provides global access to URL generation functionality.

In Templates (.phtml files):

In PHP Classes:

3. Using ViewModel (Recommended for Templates)

ViewModels provide a clean way to access URL generation in templates without using helpers or blocks.

Step 1: Add ViewModel to Block

In your module's layout XML file (e.g., view/frontend/layout/catalog_product_view.xml):

Step 2: Use in Template

In your template file (e.g., view/frontend/templates/product/view/gallery.phtml):

Alternative: Inject ViewModel Directly in Block

You can also inject the ViewModel directly in your Block class:

Then in your template:

URL Generation Examples

Basic Resize:

With Quality:

Format Conversion:

Regular URL Format:

Without Domain (Relative Path):

Service Registry

The ResizeUrlGenerationService is registered in Magento's dependency injection container (etc/di.xml) and can be accessed globally:

Note: Always prefer dependency injection over ObjectManager for better testability and performance.

Performance

Requirements

Video Model Configuration (Environment Variables)

For Veo 3.1 (Default):

For Imagen (Testing):

Note: Imagen is faster and has higher quotas, making it ideal for testing. Veo 3.1 provides higher quality and is recommended for production.

How Media App Interceptor Works

The module uses a Magento plugin to intercept requests to the Media Storage app and route resize requests to the standard HTTP app instead. This allows the module to handle /media/resize/ip/ URLs without modifying core Magento files.

Request Flow

  1. Request Arrives: A request comes to /media/resize/ip/catalog/product/image.jpg?w=300&h=300

  2. Web Server Routing: The web server routes /media/* requests to pub/get.php (configured in .magento.app.yaml)

  3. Media App Created: pub/get.php creates a Magento\MediaStorage\App\Media application instance

  4. Plugin Intercepts: The MediaPlugin::aroundLaunch() method intercepts the Media::launch() call before it executes

  5. Path Detection: The plugin checks if the request is a resize path:

    • Extracts relativeFileName from the Media app (e.g., resize/ip/catalog/product/image.jpg)
    • Checks if path starts with resize/ip/
  6. Request Transformation: If it's a resize path, the plugin:

    • Extracts the image path (everything after resize/ip/)
    • Modifies $_SERVER variables:
      • REQUEST_URI: /media/resize/ip?ip=catalog/product/image.jpg&w=300&h=300
      • PATH_INFO: /media/resize/ip
      • QUERY_STRING: ip=catalog/product/image.jpg&w=300&h=300
    • Sets $_GET['ip'] parameter
  7. HTTP App Bootstrap: The plugin creates a new Magento\Framework\App\Http application and runs it:

  8. Standard Routing: The HTTP app routes /media/resize/ip to Genaker\ImageAIBundle\Controller\Resize\Ip controller via routes.xml

  9. Controller Processing: The controller processes the resize request and returns the resized image

Plugin Configuration

The plugin is registered in etc/di.xml:

Why This Approach?

Handling Recursive Calls

The plugin includes logic to prevent infinite loops:

Testing AI Functionality

The module integrates with Google Gemini API for AI-powered image modification. Here's how to test it:

Prerequisites

  1. Set Gemini API Key:

    • Set environment variable: export GEMINI_API_KEY=your_api_key_here
    • Or configure in admin: Stores > Configuration > Genaker > Image AI Resize > Gemini API Key
  2. Admin Access Required:
    • AI prompts are only available for admin users (logged in to admin panel)
    • Or when signature validation is enabled (signature provides security)

Testing via Browser

1. Basic AI Enhancement

As an admin user, use the prompt parameter:

2. Color Enhancement

3. Style Modification

4. Background Removal

5. Object Enhancement

Testing via cURL

1. Basic Test (Admin Session Required)

2. With Signature (No Admin Required)

If signature validation is enabled, you can use AI prompts without admin access:

Testing via Integration Test

Run the integration test suite:

Expected Behavior

Successful AI Modification:

Error Cases:

AI Prompt Guidelines

Effective Prompts:

Ineffective Prompts:

Troubleshooting AI Testing

1. API Key Not Working

2. Admin Access Required Error

3. API Errors

4. No Changes Applied

5. Slow Response Times

AI Modification Limitations

Troubleshooting

Images Not Resizing

  1. Check file permissions on /pub/media/cache/resize/
  2. Verify image path is correct
  3. Check Magento logs: var/log/system.log
  4. Ensure format parameter (f) is provided

Signature Validation Failing

  1. Verify signature salt is configured correctly
  2. Ensure parameters are sorted alphabetically when generating signature
  3. Check that signature parameter is included in URL

Cache Not Working

  1. Verify directory permissions: chmod -R 755 pub/media/cache/
  2. Check disk space availability
  3. Verify Magento cache is enabled

Media App Interceptor Not Working

  1. Verify plugin is registered: Check etc/di.xml for plugin configuration
  2. Clear generated code: bin/magento setup:di:compile
  3. Check plugin is being called: Add logging to MediaPlugin::aroundLaunch()
  4. Verify route configuration: Check etc/frontend/routes.xml has frontName="media"
  5. Check Magento logs for plugin errors

Development

Module Structure

License

Copyright (c) 2024 Genaker. All rights reserved.

Support

For issues, questions, or contributions, please visit: https://github.com/Genaker/ImageResizeAI

Changelog

Version 1.2.0

Version 1.1.0

Version 1.0.0


All versions of imageaibundle with dependencies

PHP Build Version
Package Version
Requires php Version >=7.4
magento/framework Version >=102.0.0
magento/module-store Version >=101.0.0
magento/module-backend Version >=101.0.0
magento/module-config Version >=101.0.0
google-gemini-php/client Version ^2.7.4
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package genaker/imageaibundle contains the following files

Loading the files please wait ...