Skip to content

Instantly share code, notes, and snippets.

@markoheijnen
Created March 11, 2013 13:28
Show Gist options
  • Select an option

  • Save markoheijnen/5134202 to your computer and use it in GitHub Desktop.

Select an option

Save markoheijnen/5134202 to your computer and use it in GitHub Desktop.
Cropping Post Thumbnails from Top instead of Center in WordPress
<?php
class Unknown_Crop_Top_Center_Editor extends WP_Image_Editor_GD {
/**
* Processes current image and saves to disk
* multiple sizes from single source.
*
* @since 3.5.0
* @access public
*
* @param array $sizes { {'width'=>int, 'height'=>int, 'crop'=>bool}, ... }
* @return array
*/
public function multi_resize( $sizes ) {
$metadata = array();
$orig_size = $this->size;
foreach ( $sizes as $size => $size_data ) {
if( 'thumbnail' == $size && $size_data['crop'] ) {
$image = $this->_crop_top_center( $size_data['width'], $size_data['height'] );
}
else {
$image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
}
if( ! is_wp_error( $image ) ) {
$resized = $this->_save( $image );
imagedestroy( $image );
if ( ! is_wp_error( $resized ) && $resized ) {
unset( $resized['path'] );
$metadata[$size] = $resized;
}
}
$this->size = $orig_size;
}
return $metadata;
}
protected function _crop_top_center( $max_w, $max_h ) {
$dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, true );
if ( ! $dims ) {
return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions'), $this->file );
}
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
//crop from top
$src_y = 0;
$resized = wp_imagecreatetruecolor( $dst_w, $dst_h );
imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
if ( is_resource( $resized ) ) {
$this->update_size( $dst_w, $dst_h );
return $resized;
}
return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
}
}
<?php
class Unknown_Crop_Top_Center {
public function __construct() {
add_filter( 'wp_image_editors', array( $this, 'wp_image_editors' ), 100 );
}
public function wp_image_editors( $editors ) {
include_once 'editor-gd.php';
$editors2 = array(
'Unknown_Crop_Top_Center_Editor',
);
$editors = array_merge( $editors2, $editors );
return $editors;
}
}
new Marko_Crop_Top_Center;
@jmslbam
Copy link

jmslbam commented Apr 7, 2013

Thanks for the write-up! P.s. shouldn't 'new Marko_Crop_Top_Center;' be 'new Unkown_Crop_Top_Center;' ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment