Comment puis-je faire recadrer add_image_size () par le haut?
5 réponses
- votes
-
- 2011-06-24
Lagénération d'imageintermédiaireestextrêmement rigide.
image_resize()
lemaintientproche du codeet manque complètement de hooks.La seule option àpeuprèspour celaest de se connecter à
wp_generate_attachment_metadata
et d'écraser l'imagegénéréepar WPpar la vôtre (ce quinécessitera unpeu d'unefourchetteimage_resize()
).J'en aibesoinpourtravailler afin depouvoirpartager du codeplustard.
Ok,voici unexemple approximatifmaisfonctionnel. Notez que la configuration du recadrage de cettemanièrenécessite la compréhension de
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; }
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 aimage_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; }
-
ressemblebeaucoup àjouer avec lenoyau !!sounds a lot like messing with the core!!
- 1
- 2011-06-24
- Mild Fuzz
-
Non,jouer avec lenoyau changerait lafonction `image_resize`.Rarstfaisait valoir que vous deviez vous connecter auprocessus de redimensionnement,mais créez vous-même lestailles d'imagemanuellement.No, messing with the core would be changing the `image_resize` function. Rarst was making the point that you'd have to hook into the resizing process, but create the image sizes yourself manually.
- 5
- 2011-06-24
- TheDeadMedic
-
Puis-je demander si celafonctionnetoujours?Je viens d'implémenter le hook dansmonfichierfunctions.phpet j'ai configuré lesfonctions add_image_size (),mais lesimages recadrées sonttoujours recadrées au centre.May I ask if this still works? I just implemented the hook into my functions.php file and I have add_image_size() functions set-up, but the cropped images still get cropped form the center out.
- 0
- 2011-12-09
- cr0z3r
-
@ cr0z3r Jene connais aucune raisonpour laquelle celane fonctionnerapas.Maisnotez qu'ilne s'agit que d'unexemple approximatif depreuve de concept,plutôt que d'un codefiableet significatif.@cr0z3r I know of no reason why it won't work. But note that this is only rough proof-of-concept example, rather than meaningful reliable code.
- 0
- 2011-12-10
- Rarst
-
Hm,curieusement,celane fonctionnepas surmonthème - serait-ceparce queje fonctionnais localement (j'en doutefortement)?Je vais lemettreen ligneet vous lemontrerbientôt.Hm, strangely enough, it does not work on my theme - could it be because I was running locally (I highly doubt it)? I will have it up online and show it to you soon.
- 0
- 2011-12-15
- cr0z3r
-
- 2015-02-04
Le codex Wordpress a la réponse,c'est ci-dessous.
Définissez lataille de l'imageen recadrant l'imageet en définissant uneposition de recadrage:
add_image_size( 'custom-size', 220, 220, array( 'left', 'top' ) ); // Hard crop left top
Lors de la définition d'uneposition de recadrage,lapremière valeur dutableauest le x position de recadrage de l'axe,la secondeest laposition de recadrage de l'axe y.
x_crop_position accepte «gauche» «centre» ou «droite».y_crop_position accepte «haut»,«centre» ou «bas».Par défaut,ces valeurspar défaut au centre lors de l'utilisation dumode de recadrage dur.
Et aussi le codexfait référence à unepage quimontre comment lespositions des cultures agissent.
http://havecamerawilltravel.com/photographer/wordpress-thumbnail-crop
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
-
C'estgénial,devrait être la réponse acceptée,je pense!This is awesome, should be the accepted answer, I think!
- 0
- 2015-11-08
- Dalton Rooney
-
- 2012-02-19
J'ai développé une solution à ceproblème quine nécessitepas depiratage dunoyau: http://bradt.ca/archives/image-crop-position-in-wordpress/
J'ai également soumis unpatchpour core: http://core.trac.wordpress.org/ticket/19393
Ajoutez-vousen tant que Cc sur leticketpourmontrer votre soutienpour qu'il soit ajouté aunoyau.
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.
-
La solution de @ Rarstne modifiepasnonplus lesfichiersprincipaux.;)@Rarst’s solution doesn’t change core files too. ;)
- 2
- 2012-02-19
- fuxia
-
@toscho Je suppose qu'ilne voulaitpas dire que l'autre réponse change le code debase.@toscho I guess he didn't mean that the other answer changes core code.
- 1
- 2012-02-20
- kaiser
-
- 2013-01-10
Vouspouvez utiliser leplugin Thumbnail Crop Position pour sélectionner laposition de recadragede vosminiatures.
You can use the plugin Thumbnail Crop Position to select the crop position of your thumbnails.
-
- 2016-04-27
Solution alternativeici: http://pixert.com/blog/cropping-post-featured-thumbnails-from-top-instead-of-center-in-wordpress-with-native-cropping-tool/
Ajoutez simplement ce code àfunctions.php,puis utilisez leplugin "Regenerate Thumbnails" ( https://wordpress.org/plugins/regenerate-thumbnails/):
function px_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 = 0; // [[ formerly ]] ==> 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 ); } add_filter( 'image_resize_dimensions', 'px_image_resize_dimensions', 10, 6 );
Alternative solution here: http://pixert.com/blog/cropping-post-featured-thumbnails-from-top-instead-of-center-in-wordpress-with-native-cropping-tool/
Just add this code to functions.php, then use "Regenerate Thumbnails" plugin (https://wordpress.org/plugins/regenerate-thumbnails/):
function px_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 = 0; // [[ formerly ]] ==> 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 ); } add_filter( 'image_resize_dimensions', 'px_image_resize_dimensions', 10, 6 );
-
Bonjour Niente0,bienvenue à WPSEet mercipour votre réponse.Pourriez-vousmodifier votremessagepourexpliquer ce quefait votre code?Lespublications sur les sites StackExchange doiventexpliquer leur solutionet inclure uniquement des liens hors site comme références,et non comme des solutions complètes.Merciencore!Hi Niente0, welcome to WPSE and thank you for your answer. Would you mind editing your post to explain what your code does? Posts on StackExchange sites should explain their solution, and only include offsite links as references, not as entire solutions. Thanks again!
- 0
- 2016-04-27
- Tim Malone
J'ai une série d'articles,tous avec desimagesen vedette,maisje doispouvoirpersonnaliser le coin supérieur droit du recadrage.Dans ce cas,j'aibesoin qu'ils soient rognésen haut à droite,maisil serait utile de savoir également commentpositionner cepointmoi-même.
À l'heure actuelle,lafonction add_image_size ()prend son recadrage au centre de l'image.Pastoujoursjoli !!