MENU

WordPress crop di un immagine dal top

Come sempre se trovo un problema ed ho tempo condivido. Oggi mi sono ritrovato a cercare di capire come poter fare in modo che wordpress non decapitasse le persone effettuando il crop di foto verticali. Dapprima ho cercato la soluzione nel codice del template usato, invece di tratta di una caratteristica nativa. Il “problema” è contenuto in wp-include/media.php La soluzione non può essere di modificare il file perchè altrimenti al primo aggiornamento avremo un roll back della funzionalità. Si può ricorrere ad un filtro in cui si riscriva la function con le caratteristiche desiderate. Il codice si posiziona in un proprio plugin o nelle file function.php del template. Per i thumbnail già creati è necessario che essi vengano rigenerati. Per questo si può usare un plugin (es Regenerate Thumbnails)

add_filter( 'image_resize_dimensions', 'custom_image_resize_dimensions', 10, 6 );
function custom_image_resize_dimensions( $payload, $orig_w, $orig_h, $dest_w, $dest_h, $crop ){

	// Change this to a conditional that decides whether you 
	// want to override the defaults for this image or not.
	if( false )
		return $payload;

	if ( $crop ) {
		// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
		$aspect_ratio = $orig_w / $orig_h;
		$new_w = min($dest_w, $orig_w);
		$new_h = min($dest_h, $orig_h);

		if ( !$new_w ) {
			$new_w = intval($new_h * $aspect_ratio);
		}

		if ( !$new_h ) {
			$new_h = intval($new_w / $aspect_ratio);
		}

		$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);

		$crop_w = round($new_w / $size_ratio);
		$crop_h = round($new_h / $size_ratio);

		$s_x = floor( ($orig_w - $crop_w) / 2 );
		$s_y = 0; // [[ formerly ]] ==> floor( ($orig_h - $crop_h) / 2 );
	} else {
		// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
		$crop_w = $orig_w;
		$crop_h = $orig_h;

		$s_x = 0;
		$s_y = 0;

		list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
	}

	// if the resulting image would be the same size or larger we don't want to resize it
	if ( $new_w >= $orig_w && $new_h >= $orig_h )
		return false;

	// the return array matches the parameters to imagecopyresampled()
	// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
	return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );

}
1795 Visualizzazioni totali 1 Visualizzazioni odierne

Leave a Comment!

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *