Wordpress - How can I make add_image_size() crop from the top?
Wordpress codex has the answer, its below.
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 top
When 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.
And also codex references a page which shows how crop positions acts.
http://havecamerawilltravel.com/photographer/wordpress-thumbnail-crop
Intermediate image generation is extremely rigid. image_resize()
keeps it close to code and completely lacks hooks.
Pretty much only option for this is to hook into wp_generate_attachment_metadata
and overwrite WP-generated image with your own (which will need bit of a image_resize()
fork).
I need this for work so I might be able to share some code later.
Ok, here is rough, but working example. Note that setting up crop in this way requires understanding of 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;
}
I have developed a solution to this problem that does not require hacking the core: http://bradt.ca/archives/image-crop-position-in-wordpress/
I have also submitted a patch to core: http://core.trac.wordpress.org/ticket/19393
Add yourself as a Cc on the ticket to show your support for it to be added to core.