Skip to content

ORM Image Size Rule

Darryl Hein edited this page Dec 20, 2013 · 2 revisions

Rule to testing the image size.

<?php
	/**
	 * Checks the image size.
	 * Must either be the exact size or small than the max height and width.
	 * Add the rule to the ORM rules as:
	 *
	 *     array(array($this, 'image_size'), array(':validation', ':field', 680, 234)),
	 *     array(array($this, 'image_size'), array(':validation', ':field', 680, 234, TRUE)),
	 *
	 * @param   Validation  $validate    The validation object.
	 * @param   string      $field       The field that contains the local file path.
	 * @param   int         $max_width   The maximum or exact width of the image.
	 * @param   int         $max_height  The maximum or exact height of the image.
	 * @param   boolean     $exact       If the it should check exactly (TRUE) or just smaller than the dimensions (FALSE).
	 *
	 * @return  boolean
	 */
	public function image_size(Validation $validate, $field, $max_width = NULL, $max_height = NULL, $exact = FALSE) {
		if ($this->file_exists($field)) {
			try {
				// Get the width and height from the uploaded image
				list($width, $height) = getimagesize($this->get_filename_with_path($field));
			} catch (ErrorException $e) {
				// Ignore read errors
			}

			if (empty($width) || empty($height)) {
				// Cannot get image size, cannot validate
				return FALSE;
			}

			if ( ! $max_width) {
				// No limit, use the image width
				$max_width = $width;
			}

			if ( ! $max_height) {
				// No limit, use the image height
				$max_height = $height;
			}

			if ($exact) {
				// Check if dimensions match exactly
				return ($width === $max_width && $height === $max_height);
			} else {
				// Check if size is within maximum dimensions
				return ($width <= $max_width && $height <= $max_height);
			}
		}

		return FALSE;
	}

Messages file example:

<?php defined('SYSPATH') OR die('No direct access allowed.');

return array(
	'filename' => array(
		'image_size' => 'The image must be exactly 680px wide and 234px high.',
	),
);