What I would like to do is, using the Image field in core, to restrict uploaded images not just on resolution, but also on aspect ratio.

In other words, the image must be 2:3 width to height, and at least 200 by 300 pixels.

I know that Image Styles can manipulate the way an image is viewed. I'm not interested in that. Rather, I want to restrict uploads the same way that you can currently set min/max settings for resolution, I want to add aspect ratio.

My guess is that I'll need to write my own module to add a new check to Image's checks, but perhaps you know of a simpler way.

  • I'm not aware of such module either. Upvoted.
    – AKS
    Nov 15, 2012 at 3:02

1 Answer 1


My advice would be to implement a custom file validator.

To see how these are used when saving files, you can check out file_save_upload. For an example implementation that is very close to what you want to achieve, check out file_validate_image_resolution.

My super quick attempt at this

 * Validates an image upload as having a particular aspect ratio
 * @param $file
 *   - the uploaded file
 * @param $aspect_ratio
 *   - the apect ratio in the format [WIDTH]:[HEIGHT]. E.g. '3:2'
function file_validate_image_aspect(stdClass $file, $aspect_ratio = 0) {
  $errors = array();

  // Check first that the file is an image.
  if ($info = image_get_info($file->uri)) {
    if ($aspect_ratio) {
      // Check that it is smaller than the given dimensions.
      list($width, $height) = explode(':', $aspect_ratio);
      if ($width * $info['height'] != $height * $info['width']) {
        $errors[] = t('The image is the wrong aspect ratio; the aspect ratio needed is %ratio.', array('%ratio' => $aspect_ratio));

  return $errors;
  • Supremely helpful. This was the pointer in the direction I was looking for. I am going to give it a shot. Tons of thanks.
    – ezrock
    Nov 16, 2012 at 14:59
  • I looked around, and I was confused as to why file_validate_image_resolution always returned an array, even if there were no errors. Then I found the discussion of file_validate which I am linking to here for anyone else.
    – ezrock
    Nov 16, 2012 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.