Image

This component is responsible for reading images, decoding them and converting formats.


Requirements

  • PHP ^8.1

Installation

Library is available as composer repository and can be installed using the following command in a root of your project.

  • composer require bic-engine/image

Usage

Reading

Some formats (for example: ICO, DDS, etc...) can be containers and contain multiple physical images inside, so the factory returns an iterator:

$factory = new \Bic\Image\Factory();

foreach ($factory->fromPathname('path/to/image.bmp') as $index => $image) {
    // Expected: "Resolution: 640 x 480"
    echo \sprintf("Resolution: %d x %d\n", $image->getWidth(), $image->getHeight());

    // Expected: "Size: 42424 bytes"
    echo \sprintf("Size: %d bytes\n", $image->getBytes());
}

Pixel Format

$format = $image->getFormat();

Format may be one of:

  • Format::R8G8B8 for { RED, GREEN, BLUE } order, 8 bits per color component.
  • Format::B8G8R8 for { BLUE, GREEN, RED } order, 8 bits per color component.
  • Format::R8G8B8A8 for { RED, GREEN, BLUE, ALPHA } order, 8 bits per color component.
  • Format::B8G8R8A8 for { BLUE, GREEN, RED, ALPHA } order, 8 bits per color component.
  • Format::A8B8G8R8 for { ALPHA, BLUE, GREEN, RED } order, 8 bits per color component.

Format Converting

$converter = new \Bic\Image\Converter();

/**
 * Example input:
 *
 * $image = object(Bic\Image\Image) {
 *      // 3 bytes per pixel
 *      format: R8G8B8
 * }
 */
$image     = ...;

// Convert from R8G8B8 to A8B8G8R8
$to = $converter->convert($image, \Bic\Image\Format::A8B8G8R8);

/**
 * Example output:
 *
 * $to = object(Bic\Image\Image) {
 *      // 4 bytes per pixel
 *      format: A8B8G8R8
 * }
 */

Image Pixels

$image = /** object(Bic\Image\Image) */;

// Convert image to RGBA format
$image = $converter->convert($image, Format::R8G8B8A8);

$pixels = $image->getContents(); // All image pixels (binary string)
$bytes  = $image->getBytes();    // Bytes count

// Expected: 4 (for R8G8B8A8 format)
//  - 1 byte (8 bit) for RED
//  - 1 byte (8 bit) for GREEN
//  - 1 byte (8 bit) for BLUE
//  - 1 byte (8 bit) for ALPHA
$bytesPerPixel = $image->getFormat()
    ->getBytesPerPixel();

for ($i = 0; $i < $bytes; $i += $bytesPerPixel) {
    // Expected: rgba(213, 130, 10, 23)
    echo \vsprintf('rgba(%d, %d, %d, %d) ', [
        ord($pixels[$i]),
        ord($pixels[$i + 1]),
        ord($pixels[$i + 2]),
        ord($pixels[$i + 3]),
    ]);

    // Expected: #D5820A17
    echo \vsprintf('#%02X%02X%02X%02X', [
        ord($pixels[$i]),
        ord($pixels[$i + 1]),
        ord($pixels[$i + 2]),
        ord($pixels[$i + 3]),
    ]);
}

Add Decoders

$factory = new \Bic\Image\Factory();
$factory->extend(new \Bic\Image\Ico\IcoDecoder());

$images = $factory->fromPathname('path/to/image.ico');