問題描述
我有一系列的帖子,都有精選的圖片,但是我需要能夠自定義裁剪右上角。在這種情況下,我需要他們從右上方裁剪,但是也可以自己定位這一點。
目前, add_image_size() 功能正在從影像的中心拍攝。不總是漂亮!
最佳解決方案
中間影像生成非常僵硬。 image_resize()保持接近程式碼,完全沒有鉤子。
相當多的選擇是掛鉤到 wp_generate_attachment_metadata,並用你自己的 WP-generated 映像 (這將需要一個 image_resize()叉) 。
我需要這個工作,所以我可以稍後分享一些程式碼。
好的,這裡是粗糙的,但是工作的例子。請注意,以這種方式設定裁剪需要了解 imagecopyresampled()。
add_filter('wp_generate_attachment_metadata', 'custom_crop');
function custom_crop($metadata) {
$uploads = wp_upload_dir();
$file = path_join( $uploads['basedir'], $metadata['file'] ); // original image file
list( $year, $month ) = explode( '/', $metadata['file'] );
$target = path_join( $uploads['basedir'], "{$year}/{$month}/".$metadata['sizes']['medium']['file'] ); // intermediate size file
$image = imagecreatefromjpeg($file); // original image resource
$image_target = wp_imagecreatetruecolor( 44, 44 ); // blank image to fill
imagecopyresampled($image_target, $image, 0, 0, 25, 15, 44, 44, 170, 170); // crop original
imagejpeg($image_target, $target, apply_filters( 'jpeg_quality', 90, 'image_resize' )); // write cropped to file
return $metadata;
}
次佳解決方案
WordPress codex 有以下答案。
Set the image size by cropping the image and defining a crop position:
add_image_size( 'custom-size', 220, 220, array( 'left', 'top' ) ); // Hard crop left topWhen setting a crop position, the first value in the array is the x axis crop position, the second is the y axis crop position.
x_crop_position accepts ‘left’ ‘center’, or ‘right’. y_crop_position accepts ‘top’, ‘center’, or ‘bottom’. By default, these values default to ‘center’ when using hard crop mode.
而且 codex 也引用了一個頁面來顯示作物位置的作用。
http://havecamerawilltravel.com/photographer/wordpress-thumbnail-crop
第三種解決方案
我已經開發出了一個解決這個問題的方案,它不需要攻擊核心:http://bradt.ca/archives/image-crop-position-in-wordpress/
我也提交了一個補丁到核心:http://core.trac.wordpress.org/ticket/19393
將自己新增為機票上的 Cc,以顯示您將其新增到核心的支援。
第四種方案
您可以使用外掛 Thumbnail Crop Position 選擇縮圖的裁剪位置。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。