Skip to content

Instantly share code, notes, and snippets.

@mauteri
Created March 24, 2014 14:58
Show Gist options
  • Save mauteri/9741757 to your computer and use it in GitHub Desktop.
Save mauteri/9741757 to your computer and use it in GitHub Desktop.
public function closest_image_size( $width, $height, $photos ) {
foreach( $photos as $photo ) {
if( $width <= $photo['width'] && $height <= $photo['height'] ) {
$w = $photo['width'] - $width;
$h = $photo['height'] - $height;
if( !isset($source) ) {
$sum = $w + $h;
$source = $photo['source'];
} else if( $sum > ( $w + $h ) ) {
$sum = $w + $h;
$source = $photo['source'];
}
}
}
return $source;
}
@jkazimir
Copy link

public function closest_image_size( $width, $height, $photos ) {
    $current = null;

    foreach( $photos as $photo ) {
        if ( ! $this->valid_image_size( $width, $height, $photo ) ) {
            continue;
        }

        $current = $this->get_closest_image( $width, $height, $photo, $current );
    }

    return $current['source'];
}

private function valid_image_size( $width, $height, $photo ) {
    return $width <= $photo['width'] && $height <= $photo['height'];
}

private function get_image_diff_sum( $width, $height, $photo ) {
    $width_diff = $photo['width'] - $width;
    $height_diff = $photo['height'] - $height;

    return $width_diff + $height_diff;
}

private function get_closest_image( $width, $height, $photo, $current = null ) {
    if ( ! $current ) {
        return $photo;
    }

    $photo_sum = $this->get_image_diff_sum( $width, $height, $photo );
    $current_sum = $this->get_image_diff_sum( $width, $height, $current );

    if ( $current_sum > $photo_sum ) {
        return $photo;
    }

    return $current;
}

Also, this may want to be in it's own class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment