public static function resize($src, $w, $h = 0) { if (empty($src)) { return ''; } if (strstr($src, 'http') && !strstr($src, home_url())) { $src = self::sideload_image($src); } $abs = false; if (strstr($src, 'http')) { $abs = true; } //oh good, it's a relative image in the uploads folder! $path_parts = pathinfo($src); $basename = $path_parts['filename']; $ext = $path_parts['extension']; $dir = $path_parts['dirname']; $newbase = $basename . '-r-' . $w . 'x' . $h; $new_path = $dir . '/' . $newbase . '.' . $ext; $new_path = str_replace(site_url(), '', $new_path); $new_root_path = ABSPATH . $new_path; $old_root_path = ABSPATH . str_replace(site_url(), '', $src); $old_root_path = str_replace('//', '/', $old_root_path); $new_root_path = str_replace('//', '/', $new_root_path); if (file_exists($new_root_path)) { if ($abs) { return untrailingslashit(site_url()) . $new_path; } else { return TimberHelper::preslashit($new_path); } return $new_path; } $image = wp_get_image_editor($old_root_path); if (!is_wp_error($image)) { $current_size = $image->get_size(); $ow = $current_size['width']; $oh = $current_size['height']; $old_aspect = $ow / $oh; if ($h) { $new_aspect = $w / $h; if ($new_aspect > $old_aspect) { //cropping a vertical photo horitzonally $oht = $ow / $new_aspect; $oy = ($oh - $oht) / 6; $image->crop(0, $oy, $ow, $oht, $w, $h); } else { $owt = $oh * $new_aspect; $ox = $ow / 2 - $owt / 2; $image->crop($ox, 0, $owt, $oh, $w, $h); } } else { $h = $w; if ($old_aspect < 1) { $h = $w / $old_aspect; $image->crop(0, 0, $ow, $oh, $w, $h); } else { $image->resize($w, $h); } } $result = $image->save($new_root_path); if (is_wp_error($result)) { error_log('Error resizing image'); error_log(print_r($result, true)); } if ($abs) { return untrailingslashit(site_url()) . $new_path; } return $new_path; } else { if (isset($image->error_data['error_loading_image'])) { TimberHelper::error_log('Error loading ' . $image->error_data['error_loading_image']); } else { TimberHelper::error_log($image); } } return $src; }