Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coppa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Come scalare le immagini in grigio in WordPress

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Vi state chiedendo se esiste un modo per rendere automaticamente le immagini in scala di grigi in WordPress quando le caricate?

Di solito è necessario uno strumento di fotoritocco per cambiare le immagini in scala di grigi. Tuttavia, questa operazione può richiedere molto tempo, poiché è necessario modificare ogni singola immagine prima di caricarla sul sito web.

In questo articolo, vi mostreremo come scalare di grigio le immagini in WordPress durante l’uploader sul vostro sito.

Greyscale Images in WordPress

Quando utilizzare immagini in scala di grigi in WordPress?

Le immagini in scala di grigi contengono solo informazioni sulla quantità di luce presente nell’immagine. I colori delle immagini mostrano diverse tonalità di grigio, che variano tra il nero e il bianco.

In determinate situazioni, l’uso di immagini in scala di grigi può essere vantaggioso per il vostro sito web WordPress. Ad esempio, è possibile utilizzarle per migliorare la leggibilità degli oggetti mostrati nell’immagine.

D’altra parte, le immagini in scala di grigi sono comunemente utilizzate per l’elaborazione delle immagini grazie alle loro dimensioni ridotte. Ciò consente agli sviluppatori di eseguire operazioni complesse in tempi più brevi.

Detto questo, vediamo come trasformare le immagini in scala di grigi in WordPress al momento dell’uploader.

Immagini in grigio durante l’uploader in WordPress

Quando si tratta di aggiungere immagini in WordPress, è necessario modificarle prima dell’uploader utilizzando un software di editing fotografico come Photoshop e convertendo le immagini colorate in scala di grigi.

Se si hanno centinaia o migliaia di immagini da uploader, può essere necessario molto tempo per modificare manualmente ogni immagine.

Tuttavia, è possibile trasformarle automaticamente in immagini in scala di grigi al momento dell’uploader. Per iniziare, basta aggiungere il seguente codice al file functions.php del tema:

add_filter('wp_generate_attachment_metadata','rb_bw_filter');
   
function rb_bw_filter($meta) {
   
    $path = wp_upload_dir(); // get upload directory
    $file = $path['basedir'].'/'.$meta['file']; // Get full size image
   
    $files[] = $file; // Set up an array of image size urls
   
    foreach ($meta['sizes'] as $size) {
        $files[] = $path['path'].'/'.$size['file'];
    }
   
    foreach ($files as $file) { // iterate through each image size
   
        // Convert image to grayscale credit to http://ottopress.com/2011/customizing-wordpress-images/
   
        list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
        $image = wp_load_image($file);
        imagefilter($image, IMG_FILTER_GRAYSCALE);
        switch ($orig_type) {
            case IMAGETYPE_GIF:
                imagegif( $image, $file );
                break;
            case IMAGETYPE_PNG:
                imagepng( $image, $file );
                break;
            case IMAGETYPE_JPEG:
                imagejpeg( $image, $file );
                break;
        }
    }
    return $meta;
}

Un modo semplice per aggiungere codice ai file del tema è utilizzare il plugin WPCode per WordPress.

È il miglior plugin per gli snippet di codice che consente di eseguire gli snippet di codice senza dover modificare manualmente il file function.php del tema. In questo modo, non dovrete preoccuparvi di rompere il vostro sito.

WPCode

Per prima cosa, dovrete scaricare e installare il plugin gratuito WPCode sul vostro sito. Se avete bisogno di aiuto, seguite la nostra guida su come installare un plugin di WordPress.

Nota: la versione gratuita di WPCode offre tutto ciò che serve per aggiungere facilmente codice personalizzato in WordPress. Per caratteristiche più avanzate, come una libreria di snippet in cloud privata, snippet programmati, sgranati di conversione e altro ancora, potete passare a WPCode Pro.

Dopo l’attivazione, potete andare su Code Snippets ” + Aggiungi nuovo dalla vostra dashboard di WordPress.

Quindi, passare all’opzione “Aggiungi codice personalizzato (nuovo snippet)” e fare clic sul pulsante “Usa snippet”.

Add a new custom code snippet in WPCode

Quindi, inserite un nome per il vostro snippet e incollate il codice qui sopra nell’area “Anteprima del codice”.

È inoltre necessario selezionare “PHP Snippet” come tipo di codice dal menu a discesa sulla destra.

Add code snippet for grayscale images

Dopo aver inserito il codice, è possibile scorrere giù fino alla sezione “Inserimento”.

Qui si può lasciare selezionata l’opzione “Inserisci automaticamente”. In questo modo il codice verrà inserito ed eseguito automaticamente.

Insertion methods for snippets in WPCode

Infine, tornate in alto nello schermo, spostate l’interruttore da ‘Inattivo’ ad ‘Attivo’ e fate clic sul pulsante ‘Salva snippet’.

Save and activate your custom code snippet

Quindi, si può testare il codice modificando o aggiungendo una nuova pagina. Nell’editor di WordPress, fare clic sul pulsante ‘+’ e aggiungere un blocco immagine.

Ora potete caricare qualsiasi immagine sul vostro blog WordPress e la convertirà automaticamente in un’immagine in scala di grigi.

Convert images to grayscale on upload

Ci auguriamo che questo articolo vi abbia aiutato a imparare come scalare i grigi delle immagini in WordPress. Potete anche selezionare la nostra guida su come scegliere la migliore piattaforma di blog e la nostra selezione dei migliori software di web design.

Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

18 commentiLascia una risposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Tomas Kapler says

    Great tip, i would just like to mention, that for many usages it might be better to simply do this via CSS filter, e.g.
    img.bw {
    filter: grayscale(1);
    }
    you can even e.g. show b/w by default and color on hover, or you can do animation from greyscale to full color and back, e.g.
    img.bw {
    filter: grayscale(0);
    }

    img.bw.grey {
    filter: grayscale(1);
    transition-property: filter;
    transition-duration: 1s;
    }

    i also do not think, that wp_generate_attachment_metadata filter is the proper one, that should be used because of its calling in meta creation not only image creation and making second image manipulation, but the proper solution would be much longer, so i understand why it is done this way

  3. rok says

    It works nice but when uploading, WP 4.3 throws error in media library.
    i think have applied all fixes written in comments, but still error.

    my code looks like this:

    add_filter(‘wp_generate_attachment_metadata’,’themename_bw_filter’);
    function themename_bw_filter($meta) {
    $time = substr( $meta[‘file’], 0, 7); // <- get the correct time of the upload
    $file = wp_upload_dir( $time ); // <- locates the correct upload directory
    $file = trailingslashit($file[‘path’]).$meta['sizes']['slide-pic']['file'];
    if( $file ) {
    list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
    }
    $image = wp_load_image($file);
    imagefilter($image, IMG_FILTER_GRAYSCALE);
    switch ($orig_type) {
    case IMAGETYPE_GIF:
    imagegif( $image, $file );
    break;
    case IMAGETYPE_PNG:
    imagepng( $image, $file );
    break;
    case IMAGETYPE_JPEG:
    imagejpeg( $image, $file );
    break;
    }
    return $meta;
    }

  4. Tomaž Zaman says

    I know I’m a bit late to the discussion, but I just had the same problem with an error (that others report):

    imagefilter() expects parameter 1 to be resource, string given

    This happens when you try to upload image through media modal while editing a post, older than the current month which apparently confuses WordPress which directory the original image is in and which directory it should save the grayscaled image in.

    This is the solution:


    <?php
    add_filter('wp_generate_attachment_metadata','themename_bw_filter');
    function themename_bw_filter($meta) {
    $time = substr( $meta['file'], 0, 7); // <- get the correct time of the upload
    $file = wp_upload_dir( $time ); // <- locates the correct upload directory
    $file = trailingslashit($file['path']).$meta['sizes']['themename-bw-image']['file'];
    list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
    $image = wp_load_image($file);
    imagefilter($image, IMG_FILTER_GRAYSCALE);
    switch ($orig_type) {
    case IMAGETYPE_GIF:
    imagegif( $image, $file );
    break;
    case IMAGETYPE_PNG:
    imagepng( $image, $file );
    break;
    case IMAGETYPE_JPEG:
    imagejpeg( $image, $file );
    break;
    }
    return $meta;
    }

    • mklemme says

      @geertvdheide

      If you wanted to add multiple size support, try what I use:

      if ( function_exists( ‘add_theme_support’ ) ){

      add_theme_support( ‘post-thumbnails’ );

      set_post_thumbnail_size( 50, 50, true );

      add_image_size( ‘medium-thumb’, 660, ”, true );

      add_image_size( ‘large-thumb’, 960, ”, true );

      add_image_size( ‘small-thumb’, 100, ”, true );

      }

      (The height is not defined, only the width.)

      you would have to add the different names to make the function apply to them all:

      [‘medium-thumb’ , ‘large-thumb’ , ‘small-thumb’] in the filter code.

      Calling the thumbnail in your theme is the same listed in the article:

  5. geertvdheide says

    Thanks for sharing this code! Except I’m running into a weird issue when trying to implement it. It’s related to the uploaded image’s size (pixel size, meaning its dimensions). Copied the code literally to my theme’s functions.php, and it works a charm with images larger than the size specified in the add_image_size call. But when using an image smaller than or equal to the size specified, the uploader in WordPress gives me errors and doesn’t process the image size (either from the media section of the admin environment, or from a specific post or page). The error:

    Warning: imagefilter() expects parameter 1 to be resource, string given.

    Ssome other stuff in the error as well, but this seems to be the main cause. The image data given to the imagefilter function must not be valid or doesn’t exist?

    Any idea what’s causing this? The only real difference between my situation and a clean install is that I’ve also added a few other add_image_size calls for other purposes in my site. I’m also adding the same size twice (one black/white, one regular), but that doesn’t seem to be a problem with the larger images.

    • Ed Nailor says

      @GEERTVDHEIDE

      and for others that need this:

      When the script is converting the image to greyscale and the file uploaded does not fit the file size, this causes the script to break. To prevent this, simply add a quick if() conditional to make sure you have the $file.

      $file = trailingslashit($file[‘path’]).$meta[‘sizes’][‘themename-bw-image’][‘file’];
      if( $file ) {
      list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
      ——– remainder of code until ——–
      return $meta;
      }

      This will check to make sure the file size you have requested exists before it tries to convert it.

      Hope that helps!

  6. frankiegershwin says

    @Otto42 thank you! I had a bit of a hard time, actually and had to undoe it :( will pick it up tomorrow. It’s a good way to mix it up onsite

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.