JBZoo Image PHP Library

repository·master·Indexed 41 days ago

https://github.com/jbzoo/image

An object-oriented PHP library for image manipulation built on the GD extension. It features a fluent interface for resizing, cropping, filtering, watermarking, and adding text overlays. Supports various input types including filenames, Base64, binary data, and GD resources.

Tokens
2.2K
Snippets
9
Records
9
Agent score
1%

What's inside JBZoo Image

  1. Quick Start with JBZoo / Image

    master

    You can perform multiple image manipulations in a single fluent chain. This example loads a source image, applies a horizontal flip, adds text using a TTF font, creates a thumbnail, and saves the result as a PNG.

    use JBZoo//Image//Image;
    
    $img = (new Image('./example/source-image.jpg'))
        ->addFilter('flip', 'x')
        ->addFilter('text', 'Some text', './res/font.ttf')
        ->thumbnail(320, 240)
        ->saveAs('./example/dist-image.png');
  2. Install JBZoo / Image via Composer

    master

    Install the library using Composer to add it to your project dependencies.

    composer require jbzoo/image
  3. Initialize an Image object

    master

    The Image class can be instantiated using several different input types:

    • Filename: A path to an image file.
    • Base64: A data URI string (e.g., data:image/gif;base64,...).
    • Image string: A raw base64 encoded string.
    • Binary data: Raw binary image data.
    • GD Resource: An existing PHP GD image resource.
    // Filename
    $img = new Image('./path/to/image.png');
    
    // Base64 format
    $img = new Image('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
    
    // Image string
    $img = new Image('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
    
    // Some binary data
    $imgBin = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
    $img = new Image($imgBin);
    
    // Resource
    $imgRes = imagecreatefromjpeg('./some-image.jpeg');
    $img = new Image($imgRes);
  4. Apply image filters

    master

    Use addFilter(name, ...args) to apply built-in effects. You can also pass a closure to implement custom logic using the GD resource.

    // Built-in filters
    $img->addFilter('sepia');
    $img->addFilter('grayscale');
    $img->addFilter('desaturate', 50);
    $img->addFilter('pixelate', 8);
    $img->addFilter('blur', Filter::BLUR_GAUS, 2);
    $img->addFilter('brightness', 100);
    $img->addFilter('contrast', 50);
    $img->addFilter('colorize', '#FF0000', .5);
    $img->addFilter('rotate', 90);
    $img->addFilter('flip', 'x'); // Horizontal flip
    
    // Custom filter handler
    $img->addFilter(function ($image, $blockSize) {
        imagefilter($image, IMG_FILTER_PIXELATE, $blockSize, true);
    }, 2);
  5. Overlay watermarks

    master

    Overlay an image onto the current image using the overlay method. Parameters include the file path, position, opacity, and X/Y offsets.

    // Overlay watermark.png at 50% opacity at the bottom-right with 10px margins
    $img->overlay('./image/watermark.png', 'bottom right', .5, -10, -10);
  6. Resize and crop images

    master

    The library provides several ways to change image dimensions:

    • resize(w, h): Resize to exact dimensions.
    • thumbnail(w, h, [top]): Resize and crop to exact dimensions. If the third parameter is true, it crops from the TOP; otherwise, it crops the CENTER.
    • fitToWidth(w): Shrink width while maintaining aspect ratio.
    • fitToHeight(h): Shrink height while maintaining aspect ratio.
    • bestFit(w, h): Shrink proportionally to fit inside a bounding box.
    • crop(l, t, r, b): Crop a portion using left, top, right, and bottom offsets.
    $img->resize(320, 200);
    $img->thumbnail(100, 75);        // Crop CENTER
    $img->thumbnail(100, 75, true);  // Crop TOP
    $img->fitToWidth(320);
    $img->fitToHeight(200);
    $img->bestFit(500, 500);
    $img->crop(100, 100, 400, 400);
  7. Retrieve image data and metadata

    master

    Use utility methods to extract information or export the image in different formats.

    // Exporting
    $img->getBase64('jpeg', 85);      // Base64 string of JPEG at 85% quality
    $img->getBinary('webp');         // Binary data in WebP format
    $img->getImage();                // Get the raw GD Image resource
    
    // Metadata
    $img->getWidth();                // Width in px
    $img->getHeight();               // Height in px
    $img->isPortrait();              // Check orientation
    $img->isJpeg();                  // Check if format is JPEG
    $imgInfo = $img->getInfo();       // Get array of all properties (filename, width, height, mime, exif, etc.)
  8. Save and convert images

    master

    Images must be saved after manipulation. You can save to the original file or a new path. You can also change the format by changing the file extension in saveAs().

    // Save to original file
    $img->save();
    $img->save(90); // Specify quality (0-100)
    
    // Save as new file
    $img->saveAs('./some-path/new-image.jpg');
    $img->saveAs('./some-path/new-image.jpg', 90); // Specify quality
    $img->saveAs('./some-path/new-image.png'); // Convert to PNG via extension
  9. Add text overlays

    master

    Add text to an image using the text filter. You must provide the text string and a path to a .ttf font file. You can pass an optional array of parameters for styling.

    $img->addFilter(
        'text',                             // Filter name
        'Some image description',           // Text to render
        './resources/font.ttf',              // TTF font file
        [
            'font-size'      => 48,          // Font size in px
            'color'          => '#ff7f00',    // Color string or array for gradients
            'stroke-color'   => '#f00',      // Stroke color
            'stroke-size'    => 3,           // Stroke size in px
            'stroke-spacing' => 5,          // Letter spacing
            'offset-x'       => -140,        // X offset
            'offset-y'       => 100,        // Y offset
            'position'       => 't',        // Position: top|t|... (use Helper::position() for details)
            'angle'          => 0,          // Angle for each letter
        ]
    );