get_size(); list($num, $den) = array_map('floatval', explode(':', $ratio)); $target_w_h = $num / $den; $src_w = $size['width']; $src_h = $size['height']; if ($subject_bbox) { // bbox = [x,y,w,h] in source pixels. Expand to ratio. list($x, $y, $w, $h) = $subject_bbox; $cx = $x + $w / 2; $cy = $y + $h / 2; $want_w = max($w, $h * $target_w_h); $want_h = $want_w / $target_w_h; $nx = max(0, min($src_w - $want_w, $cx - $want_w / 2)); $ny = max(0, min($src_h - $want_h, $cy - $want_h / 2)); $editor->crop((int) $nx, (int) $ny, (int) $want_w, (int) $want_h); } else { // centered crop. $src_ratio = $src_w / $src_h; if ($src_ratio > $target_w_h) { $new_w = (int) ($src_h * $target_w_h); $nx = (int) (($src_w - $new_w) / 2); $editor->crop($nx, 0, $new_w, $src_h); } else { $new_h = (int) ($src_w / $target_w_h); $ny = (int) (($src_h - $new_h) / 2); $editor->crop(0, $ny, $src_w, $new_h); } } return $editor; } // Save an in-memory editor to the WP uploads dir, return [url, path]. public static function save_as($editor, $filename, $mime = 'image/jpeg', $quality = 88) { $uploads = wp_upload_dir(); $dir = trailingslashit($uploads['path']) . 'acpimg'; if (!is_dir($dir)) wp_mkdir_p($dir); $path = $dir . '/' . $filename; $editor->set_quality($quality); $saved = $editor->save($path, $mime); if (is_wp_error($saved)) return $saved; $url = trailingslashit($uploads['url']) . 'acpimg/' . $filename; return ['url' => $url, 'path' => $saved['path']]; } // Quick filetype check by extension. public static function ext($path) { return strtolower(pathinfo($path, PATHINFO_EXTENSION)); } public static function is_webp_or_avif($path_or_url) { $ext = self::ext($path_or_url); return in_array($ext, ['webp', 'avif'], true); } }