我编写了一个函数来获取图像路径,在其末尾添加一些文本,然后将其重新组合在一起。在将新文本附加到图像后,我正在尝试编写一个 if else 分支来测试文件是否存在。
例如,如果我请求图像路径:
http://example.com/image1.jpg
可以修改成这样:
http://example.com/image1-150x100.jpg
该函数适用于 WordPress,因此采用 $post->ID 参数、自定义字段名称、预期目标的宽度和高度。
这是功能:
function get_galleria_image ( $post_id, $customFieldName, $width, $height ) {
$imagePath = get_post_meta($post_id, $customFieldName, true);
$splitImage = explode('.', $imagePath);
$count = count($splitImage);
$firstHalf = array_slice($splitImage, 0, $count-1);
$secondHalf = array_slice($splitImage, $count-1);
$secondHalf[0] = '-' . $width . 'x' . $height . '.' . $secondHalf[0];
$firstHalfJoined = implode('.', $firstHalf);
$completedString = $firstHalfJoined . $secondHalf[0];
// if the filename with the joined string does not exist, return the original image
if (file_exists($completedString)){
return $completedString;
} else {
return $imagePath;
}
}
我知道这很粗糙,因此欢迎任何压缩此代码并使其“更好”的想法。我发现该函数始终返回原始图像路径。file_exists() 可以采用像“http://example.com/image1.jpg”这样的绝对路径,还是只接受根样式的绝对路径,如“/path/to/file/image1.jpg”?