PHPackages                             rkr/image - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. rkr/image

ActiveLibrary[Image &amp; Media](/categories/media)

rkr/image
=========

A simple image manipulation library using gd-lib

0.2.0(2w ago)31.5kMITPHPPHP &gt;= 8.1

Since Aug 15Pushed 2w ago2 watchersCompare

[ Source](https://github.com/rkrx/php-image-manipulation)[ Packagist](https://packagist.org/packages/rkr/image)[ RSS](/packages/rkr-image/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (10)Dependencies (4)Versions (15)Used By (0)

php-image-manipulation
======================

[](#php-image-manipulation)

A simple image manipulation library using gd-lib

Installation
------------

[](#installation)

```
composer require rkr/image
```

Usage (PHP 8.1+)
----------------

[](#usage-php-81)

More information is also available in the [generated docs](docs/classes/Kir/Image/Image.md).

### Resample proportionally

[](#resample-proportionally)

```
use Kir\Image\Image;
$image = Image::loadFromFile('image.png');

$newImage = $image->getCopy();
$newImage->resizeProportional(width: 500);
$newImage->saveAsWebP(filename: 'new-image-width-500.webp');

$newImage = $image->getCopy();
$newImage->resizeProportional(height: 500);
$newImage->saveAsWebP(filename: 'new-image-height-500.webp');

$newImage = $image->getCopy();
$newImage->resizeProportional(width: 500, height: 500);
$newImage->saveAsWebP(filename: 'new-image-largest-side-to-500.webp');
```

### Enlarge canvas

[](#enlarge-canvas)

```
use Kir\Image\Image;
$image = Image::loadFromFile('image.png');
$image->resizeProportional(width: 500, height: 500);
$image->resizeCanvasCentered(width: 500, height: 500);
$image->saveAsWebP(filename: '500x500.webp');
```

### Auto crop image with optional border

[](#auto-crop-image-with-optional-border)

The crop function is solved via a separate algorithm. If a border width is specified as a percentage, but too much of the original graphic was cut away during the actual cropping, then this image portion is retained in the border area.

```
use Kir\Image\Image;
use Kir\Image\Color;
$image = Image::loadFromFile('image.png');

$image->getCopy()
    ->crop(
        threshold: 15, // 0..255 color scale
        borderPercent: 3, // %
        backgroundColor: Color::whiteOpaque(),
    )
    ->resizeProportional(width: 500, height: 500)
    ->resizeCanvasCentered(width: 500, height: 500)
    ->saveAsWebP(filename: '500x500.webp');
```

### Text rendering (TrueType)

[](#text-rendering-truetype)

Requires GD with FreeType support and a `.ttf`/`.otf` font file.

```
use Kir\Image\Image;
use Kir\Image\Color;

$image = Image::create(600, 240, Color::whiteOpaque());
$image->text(
    text: 'Hello World',
    x: 300,
    y: 120,
    fontFile: __DIR__ . '/Roboto-Regular.ttf',
    fontSize: 42,
    color: Color::fromRGB(0, 0, 0),
    angle: 0,
    anchor: 'center',
);
$image->saveAsPng(filename: 'text.png');
```

Image API reference (all methods)
---------------------------------

[](#image-api-reference-all-methods)

All methods throw `Kir\Image\ImageRuntimeException` on invalid input / unsupported operations.

### Static methods

[](#static-methods)

- `public static function getImageType(string $filename): int`
    Detects the image type constant (e.g. `IMAGETYPE_PNG`) for a file.
- `public static function getDefaultImageExtension(string $filename): ?string`
    Returns a default extension (e.g. `"png"`) detected via `mime_content_type`.
- `public static function supportsFormat(int|string $format, bool $forWriting = false): bool`: Checks runtime read support by `IMAGETYPE_*` or extension; set `$forWriting` for the library’s output formats.
- `public static function getSupportedFormats(bool $forWriting = false): array`: Returns canonical names for the formats supported by the current GD build and this library.
- `public static function loadFromString(string $data): Image`
    Loads an image from raw bytes.
- `public static function loadFromFile(string $filename): Image`
    Loads AVIF, BMP, GIF, JPEG, PNG, WBMP, WebP, XBM, XPM, TGA, GD and GD2 images from a file path. Optional formats must be enabled in the installed GD build.
- `public static function create(int $width, int $height, ?Color $color = null, ?int $imageType = null): Image`
    Creates a new blank image (defaults to a transparent white background).

### Object lifecycle

[](#object-lifecycle)

- `public function __construct(\GdImage $resource, ?int $type = null)`
    Wraps an existing GD image object (prefer `loadFromFile()` / `create()` if possible).

### Basic information

[](#basic-information)

- `public function getGdImage(): \GdImage`
    Returns the underlying GD image.
- `public function getWidth(): int`
    Returns the image width in pixels.
- `public function getHeight(): int`
    Returns the image height in pixels.
- `public function getFileType(): ?int`
    Returns the last known `IMAGETYPE_*` (if available).
- `public function getMimeType(): ?string`
    Returns a MIME type like `"image/png"` if the file type is known.
- `public function getCopy(): self`
    Creates a full copy of the image.

### Compositing / paste

[](#compositing--paste)

- `public function placeImageOn(Image|\GdImage $targetImage, int $offsetX = 0, int $offsetY = 0): self`
    Deprecated alias for `pasteOn()`.
- `public function pasteOn(Image|\GdImage $targetImage, int $offsetX = 0, int $offsetY = 0): self`
    Copies this image onto the given target.

### Pixel inspection

[](#pixel-inspection)

- `public function getRedColorAt(int $x, int $y): int`
- `public function getGreenColorAt(int $x, int $y): int`
- `public function getBlueColorAt(int $x, int $y): int`
- `public function getAlphaAt(int $x, int $y): int`
    Returns alpha in 0..255 (0 transparent, 255 opaque).
- `public function getChannelColorAt(int $x, int $y, int $bitMask): int`
    Low-level helper used by the channel getters.

### Filters / color operations

[](#filters--color-operations)

- `public function greyscale(): self`
    Applies `IMG_FILTER_GRAYSCALE`.
- `public function applyAlphaMaskFromGreyscaleImage(Image $mask): self`
    Uses a same-sized greyscale mask’s channel value as alpha for the current image.
- `public function adjustColors(): self`
    Stretches colors to fill the full 0..255 range; constant-color images remain unchanged.

### Geometric transformations

[](#geometric-transformations)

- `public function rotate(float $angle, ?Color $backgroundColor = null): self`: Rotates anticlockwise, expands the canvas and uses transparent white for uncovered areas by default.
- `public function flip(int $mode = IMG_FLIP_HORIZONTAL): self`: Flips using `IMG_FLIP_HORIZONTAL`, `IMG_FLIP_VERTICAL` or `IMG_FLIP_BOTH`.

### Auto-crop / content detection

[](#auto-crop--content-detection)

- `public function crop(int $threshold = 15, int $borderPercent = 0, ?Color $backgroundColor = null): self`
    Removes excess whitespace around the detected inner object and optionally adds a border.
- `public function detectInnerObject(int $threshold = 15): array`
    Returns measures: `left`, `top`, `right`, `bottom`, `width`, `height`.

### Canvas resizing (crop/pad)

[](#canvas-resizing-croppad)

- `public function resizeCanvas(int $width, int $height, ?int $offsetX = null, ?int $offsetY = null, ?Color $backgroundColor = null): self`
    Changes canvas size; crops or pads with background color (offset defaults to centered).
- `public function resizeCanvasCentered(int $width, int $height, ?Color $backgroundColor = null): self`
    Centered convenience wrapper for `resizeCanvas()`.

### Resampling / proportional resizing

[](#resampling--proportional-resizing)

- `public function resize(?int $width = null, ?int $height = null): self`
    Resamples to exact size (non-proportional); omitted dimensions keep current size.
- `public function cropToCover(int $width, int $height): self`: Resamples and center-crops to cover the exact target dimensions.
- `public function shrinkProportional(?int $width = null, ?int $height = null): self`
    Only shrinks if the image is larger than the target rectangle.
- `public function resizeProportional(?int $width = null, ?int $height = null): self`
    Resizes proportionally to fit inside the target rectangle.
- `public function enlargeProportional(?int $width = null, ?int $height = null): self`
    Resizes proportionally aiming to enlarge to the target rectangle.

### Drawing

[](#drawing)

- `public function fill(int $x, int $y, Color $color): self`
    Flood-fill starting at the given pixel.
- `public function rectangle(int $x, int $y, int $width, int $height, Color $color): self`
    Draws a filled rectangle.

### Text rendering (TrueType)

[](#text-rendering-truetype-1)

Requires GD with FreeType support.

- `public function measureText(string $text, string $fontFile, float $fontSize, float $angle = 0.0): array`
    Returns `width`, `height`, `offsetX`, `offsetY` and the raw `bbox` array (from `imagettfbbox()`).
- `public function text(string $text, int $x, int $y, string $fontFile, float $fontSize, Color $color, float $angle = 0.0, string $anchor = 'top-left'): self`
    Draws TTF text; anchors include `top-left`, `center`, `bottom-right`, `baseline-left`, etc.

### Alpha/background

[](#alphabackground)

- `public function removeAlphaBackground(?Color $color = null): self`
    Replaces transparency with an opaque background color (default: white).

### Saving / output

[](#saving--output)

- `public function saveAs(?string $filename, ?int $explicitType = null): self`
    Saves based on extension (or forced type) and defaults to the last known file type.
- `public function saveAsPng(?string $filename = null): self`
- `public function saveAsJpeg(?string $filename = null, int $quality = 100): self`
- `public function saveAsGif(?string $filename = null): self`
- `public function saveAsWebP(?string $filename = null, int $quality = 100): self`
- `public function saveAsBmp(?string $filename = null): self`
- `public function saveAsString(?int $imageType = null, int $quality = 100): string`
    Encodes the image into bytes (useful for HTTP responses or storage).

### Internal helpers (private, not part of the public API)

[](#internal-helpers-private-not-part-of-the-public-api)

- `private static function temporaryRemoveAlphaChannel(Image $srcIm, \Closure $fn): void`
    Used by JPEG/GIF/BMP saving to replace alpha with an opaque background.
- `private static function createResource(int $width, int $height, ?Color $color = null): \GdImage`
    Creates a new `\GdImage` and initializes alpha handling.
- `private static function createGdColorFromColor(\GdImage $resource, Color $color): int`
    Converts `Color` into a GD color index for the given image resource.

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance96

Actively maintained with recent releases

Popularity23

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~139 days

Recently: every ~364 days

Total

14

Last Release

19d ago

PHP version history (2 changes)0.1PHP &gt;= 7.4

0.2.0PHP &gt;= 8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/7f83d7e57a4bf3f1309680dbfbbf2d022f0ee6dae64a4b3bdfbed1226f2f6bef?d=identicon)[rkr](/maintainers/rkr)

---

Top Contributors

[![rkrx](https://avatars.githubusercontent.com/u/5672982?v=4)](https://github.com/rkrx "rkrx (39 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rkr-image/health.svg)

```
[![Health](https://phpackages.com/badges/rkr-image/health.svg)](https://phpackages.com/packages/rkr-image)
```

###  Alternatives

[goat1000/svggraph

Generates SVG graphs

135931.0k3](/packages/goat1000-svggraph)[stefangabos/zebra_image

A single-file, lightweight PHP library designed for efficient image manipulation featuring methods for modifying images and applying filters

138121.6k7](/packages/stefangabos-zebra-image)[treinetic/imageartist

ImageArtist is a php gd Wrapper which makes Image manipulation insanely easy, we introduce ImageArtist as Photoshop for php

8783.2k](/packages/treinetic-imageartist)[johncarter/filament-focal-point-picker

An image focal point picker for Filament Admin.

4431.7k1](/packages/johncarter-filament-focal-point-picker)[yk/laravel-ocr

A wrapper for gocr.

1356.6k](/packages/yk-laravel-ocr)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
