Skip to main content

Image lib

Utility for loading and processing images (GIF, JPEG, PNG): proportional resize, square crop, image and text watermarks, saving, and output.

Access the library via the shared lib instance:

// Create a working instance by loading a source image
$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg'); // instance of image_lib

// or
$img = $this->lib->image; // instance of image_lib
$img->load(PHOTO_PATH);

Notes:

  • Supported formats: GIF, JPEG/JPG, PNG.
  • Requires the GD extension. For text watermarks (imagettftext), GD must be compiled with FreeType and you must provide a .ttf font file path.
  • Many methods return false if no image is loaded (e.g., do_resize() without a preceding load()/instance() call).
  • The library keeps the original image resource and the last processed (resized) resource separately.
    • Use save($dest, $overwrite, $dynamic_save = true) to save the last processed result.
    • output() renders the original image resource; if you need to output the processed image, save it first and serve that file.

instance()

Create a new image_lib instance and load the image in one call.

  • Parameters: string $src_file
  • Returns: image_lib — an instance with the source attempted to be loaded

Behavior:

  • Internally calls load($src_file). If the file is unreadable or unsupported, the instance is returned but subsequent operations will return false.

Usage Example:

$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg');
if (!$img->do_resize(800)) {
// handle failure (invalid or unreadable image, etc.)
}

load()

Load an image from file.

  • Parameters: string $src_file
  • Returns: booltrue on success; false if unreadable or not an image

Usage Example:

$img = $this->lib->image;
if (!$img->load(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg')) {
die('Invalid image');
}

is_image()

Check whether a file is a supported image.

  • Parameters: string $src_file
  • Returns: bool

Behavior highlights:

  • Uses getimagesize() and accepts only types 1 (GIF), 2 (JPEG), or 3 (PNG).

Usage Example:

if ($this->lib->image->is_image(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg')) {
// ok
}

do_resize()

Resize the image, optionally as a square and/or with watermarks. Prepares the in-memory result for saving.

  • Parameters:
    • int $size — target size; see behavior
    • bool $is_square = false — crop to a square thumbnail
    • array|bool $watermark = false — image watermark options
    • array|bool $watermark_text = false — text watermark options
  • Returns: bool

Behavior:

  • Proportional resize: the longer side becomes $size, the shorter side is scaled proportionally. If both sides are already smaller than $size, the original size is kept.
  • Square crop ($is_square = true):
    • Landscape images are center-cropped horizontally; portrait images are cropped from the top-left square region.
    • The resulting image has $size x $size dimensions.
  • Image watermark (when $watermark is provided):
    • Keys:
      • image (string, required): path to watermark image (PNG/JPEG/GIF)
      • position (string, optional): one of c, tr, br, tl, bl (default: bottom-right)
      • margin (int, optional): margin in pixels from edges (ignored in center)
  • Text watermark (when $watermark_text is provided):
    • Keys:
      • text (string, required)
      • font (string, required): path to a .ttf font file
      • size (int, default 10)
      • color (string, default "000000"): 6-hex RGB, with or without leading #
      • position (string, default bottom-right): c, tr, br, tl, bl
      • margin (int, default 0)
      • angle (int, default 0)

Usage Examples:

// 1) Simple proportional resize (longer side = 1200), then save a result
$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg');
$img->do_resize(1200);
$img->save('D:\\public\\images\\', true, true); // dynamic_save = true saves the resized result

// 2) Square thumbnail (200x200) with bottom-right image watermark, 10px margin
$wm = [
'image' => 'D:\\assets\\wm.png',
'position' => 'br',
'margin' => 10,
];
$img = $this->lib->image->instance('TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg'');
$img->do_resize(200, true, $wm);
$img->save('TK_APP_PATH . 'upload' . TK_DS . '200_', true, true);

// 3) Add a text watermark (top-right, red, 12pt)
$wmText = [
'text' => '© ACME',
'font' => TK_APP_PATH . 'upload' . TK_DS . 'fonts' .TK_DS . 'OpenSans-Regular.ttf',
'size' => 12,
'color' => '#FF0000',
'position' => 'tr',
'margin' => 8,
];
$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg');
$img->do_resize(1024, false, false, $wmText);
$img->save('TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg', true, true);

resize_image()

Low-level resample helper used by do_resize().

  • Parameters: array $options
  • Returns: bool

Expected keys in $options:

  • width, height — destination size (required)
  • img_width, img_height — source crop size (required)
  • Optional crop offsets: x1, y1, x2, y2 (default 0)

Notes:

  • Handles PNG alpha and GIF transparency preservation.

calculate_size()

Compute proportional destination size for a given target edge.

  • Parameters: int $size
  • Returns: array|bool — array with keys width, height, img_width, img_height or false on invalid input

Behavior:

  • Sets the longer edge to $size and preserves an aspect ratio.
  • If the image is already smaller than $size in both dimensions, returns the original size.

calculate_square_size()

Compute square crop/resample options for a $size x $size output.

  • Parameters: int $size
  • Returns: array|bool

Behavior:

  • Uses the shorter side as the square crop side.
  • For landscape images, crops are centered horizontally; for portrait images, crops from the top-left square.

watermark_image()

Overlay another image as a watermark.

  • Parameters: string $w_image, bool $dynamic_watermark = false, mixed $pos = null, mixed $margin = null
  • Returns: bool

Behavior:

  • When $dynamic_watermark = true, applies to the last processed (resized) image; otherwise, to the original.
  • Positions: c (center), tr, br, tl, bl. Margin is ignored for center.

Usage Example:

$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg');
$img->do_resize(800); // prepare result
$img->watermark_image(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg', true, 'br', 10); // apply to the resized result
$img->save(TK_APP_PATH . 'upload' . TK_DS . 'photo_wm.jpg', true, true);

watermark_text()

Draw a text watermark using a TTF font.

  • Parameters: string $text, string $font, int $size = 10, string $color = '000000', string $pos = 'br', int $margin = 0, int $angle = 0, bool $dynamic_watermark = false
  • Returns: bool

Notes:

  • $font must be a path to a .ttf file.
  • $color can be RRGGBB or #RRGGBB.
  • Position codes same as watermark_image().

save()

Save the image resource to a file.

  • Parameters: string|null $dest_file = null, bool $overwrite = false, bool $dynamic_save = false
  • Returns: bool

Behavior:

  • If $dest_file is null, saves to the original file path.
  • If $dest_file is a directory path, the original file name is used in that directory.
  • Otherwise $dest_file must include a valid extension (png, gif, jpg, jpeg).
  • Existing files are not overwritten unless $overwrite = true.
  • When $dynamic_save = true, saves the last processed (resized/watermarked) result; otherwise saves the original image resource.

Usage Examples:

// Save the original image under a new name
$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg');
$img->save(TK_APP_PATH . 'upload' . TK_DS . 'another_dir' . TK_DS . 'photo.jpg');

// Save the processed result
$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg');
$img->do_resize(1200);
$img->save(TK_APP_PATH . 'upload' . TK_DS . 'photo_1200.jpg', true, true);

output()

Send the original image to the browser with proper headers.

  • Parameters: string|bool $output_name = false
  • Returns: void

Behavior:

  • Sets Content-Type to the image MIME type and Content-Disposition as attachment.
  • If $output_name is provided, the appropriate extension is appended automatically; otherwise the original file name is used.
  • Outputs the original image resource. To output a processed result, first save it (save(..., true, true)) and then serve that file.

Usage Example:

$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg');
$img->output('download'); // sends download.jpg/.png/.gif

save_resized()

Batch-resize into multiple variants and save each result with a size-based prefix.

  • Parameters: array $size_options, string|null $destination = null, bool $random_name = true
  • Returns: string — base file name used for generated variants

Input format for $size_options (each item merged with defaults):

[
[
'size' => 1200, // required, int
'crop_square' => false, // optional
'watermark' => false, // optional (same format as in do_resize)
'watermark_text' => false, // optional (same format as in do_resize)
// 'destination' => TK_APP_PATH . 'upload' . TK_DS . 'another_dir' . TK_DS . 'photo.jpg' // optional per-item override
],
[
'size' => 300,
'crop_square' => true,
],
]

Behavior:

  • If $random_name = true, a random base file name is generated using the original extension; otherwise the original name is reused.
  • For each item:
    • Processes the image via do_resize() with the provided options.
    • Saves to {destination}{prefix}{base} where:
      • Prefix is {size}_ or {size}_sq_ when crop_square = true.
  • Returns the base file name, e.g., a1b2c3d4.jpg.

Usage Example:

$img = $this->lib->image->instance(TK_APP_PATH . 'upload' . TK_DS . 'photo.jpg');
$base = $img->save_resized([
['size' => 1200],
['size' => 800],
['size' => 300, 'crop_square' => true],
], TK_APP_PATH . 'upload' . TK_DS . 'another_dir' . TK_DS . 'photo.jpg', true);
// Files created:
// another_dir/1200_a1b2c3d4.jpg
// another_dir/800_a1b2c3d4.jpg
// another_dir/300_sq_a1b2c3d4.jpg

Dependencies and environment

  • Requires the shared lib instance (see: The library instance and usage).
  • Uses $this->lib->file for extension checks and path handling.
  • Requires PHP GD extension. For text watermarks, ensure FreeType support.

Tips

  • Always call save(..., true, true) after do_resize() to persist the processed result.
  • Use consistent fonts and colors for text watermarks; prefer transparent PNGs for image watermarks.
  • When generating multiple sizes, prefer save_resized() for convenience and consistent naming.

Caveats

  • In this library version, save() invokes the encoder only for non‑PNG types; saving PNGs may be a no‑op depending on the build. If you need PNG output, consider converting to JPEG when saving, or update the library to a version that supports writing PNG files.