Esempio n. 1
0
function crop_media($image_media, $width, $height)
{
    if (empty($image_media)) {
        return;
    }
    list($image_path, $modified_path, $modified_media) = _media_filenames($image_media, '-crop-' . $width . 'x' . $height);
    if (!file_exists($image_path)) {
        return;
    }
    if (!file_exists($modified_path) || filemtime($modified_path) < filemtime($image_path)) {
        $image = new GDImage($image_path);
        // preserve aspect ratio
        $old_width = (double) $image->width;
        $old_height = (double) $image->height;
        $old_ratio = $old_width / $old_height;
        $new_width = (double) $width;
        $new_height = (double) $height;
        $new_ratio = $width / $height;
        // figure out whether to keep width or height.
        if ($old_ratio < $new_ratio) {
            $image->resize($width, 0, false);
            $crop = ($image->height - $height) / 2;
            $image->crop(0, $crop, $width, $crop + $height);
        } else {
            if ($old_ratio > $new_ratio) {
                $image->resize(0, $height, false);
                $crop = ($image->width - $width) / 2;
                $image->crop($crop, 0, $crop + $width, $height);
            }
        }
        // end preserve aspect ratio
        $image->save($modified_path);
    }
    return $modified_media;
}