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

Como fazer imagens em escala de cinza no WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Você está se perguntando se existe uma maneira de colocar imagens em escala de cinza automaticamente no WordPress quando você as carrega?

Normalmente, você precisa de uma ferramenta de edição de fotos para alterar suas imagens para tons de cinza. No entanto, isso pode ser demorado, pois você precisará editar cada imagem individualmente antes de carregá-la em seu site.

Neste artigo, mostraremos como fazer o upload de imagens em escala de cinza no WordPress para o seu site.

Greyscale Images in WordPress

Quando você deve usar imagens em tons de cinza no WordPress?

As imagens em escala de cinza contêm apenas informações sobre a quantidade de luz na imagem. As cores da imagem mostram diferentes tons de cinza, variando entre preto e branco.

Em determinadas situações, o uso de imagens em tons de cinza pode ser benéfico para seu site WordPress. Por exemplo, você pode usá-las para melhorar a legibilidade dos objetos mostrados na imagem.

Por outro lado, as imagens em escala de cinza são comumente usadas para processamento de imagens devido ao seu pequeno tamanho. Isso permite que os desenvolvedores executem operações complexas em um tempo mais curto.

Dito isso, vamos ver como você pode transformar suas imagens em tons de cinza no WordPress ao carregá-las.

Imagens em cinza ao fazer upload no WordPress

Quando se trata de adicionar imagens no WordPress, você precisa editá-las antes de fazer o upload usando um software de edição de fotos como o Photoshop e converter imagens coloridas em escala de cinza.

Se você tiver centenas ou milhares de imagens para carregar, pode levar muito tempo para editar cada imagem manualmente.

No entanto, você pode transformá-las automaticamente em imagens em tons de cinza após o upload. Para começar, tudo o que você precisa fazer é adicionar o seguinte código ao arquivo functions.php do seu 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;
}

Uma maneira simples de adicionar código aos arquivos de tema é usar o plug-in WPCode para WordPress.

É o melhor plug-in de snippets de código que ajuda a executar snippets de código sem a necessidade de editar manualmente o arquivo function.php do seu tema. Dessa forma, você não precisa se preocupar em danificar seu site.

WPCode

Primeiro, você precisará fazer o download e instalar o plug-in gratuito WPCode em seu site. Se precisar de ajuda, siga nosso guia sobre como instalar um plug-in do WordPress.

Observação: a versão gratuita do WPCode oferece tudo o que você precisa para adicionar facilmente códigos personalizados no WordPress. Para obter recursos mais avançados, como uma biblioteca de snippets em nuvem privada, snippets programados, pixels de conversão e muito mais, você pode fazer upgrade para o WPCode Pro.

Após a ativação, você pode ir até Code Snippets ” + Add New no painel do WordPress.

Em seguida, navegue até a opção “Add Your Custom Code (New Snippet)” (Adicionar seu código personalizado (novo snippet)) e clique no botão “Use snippet” (Usar snippet).

Add a new custom code snippet in WPCode

Em seguida, digite um nome para o snippet e cole o código acima na área “Code Preview” (Visualização de código).

Você também precisa selecionar “PHP Snippet” como o tipo de código na lista suspensa à direita.

Add code snippet for grayscale images

Depois de inserir o código, você pode rolar para baixo até a seção “Inserção”.

Aqui, você pode deixar a opção “Auto Insert” (Inserção automática) selecionada. Isso inserirá e executará automaticamente o código para você.

Insertion methods for snippets in WPCode

Por fim, volte à parte superior da tela e alterne a chave de “Inativo” para “Ativo” e clique no botão “Salvar snippet”.

Save and activate your custom code snippet

Em seguida, você pode testar o código editando ou adicionando uma nova página. Quando estiver no editor do WordPress, clique no botão “+” e adicione um bloco de imagem.

Agora você pode carregar qualquer imagem em seu blog do WordPress e ela será automaticamente convertida em uma imagem em tons de cinza.

Convert images to grayscale on upload

Esperamos que este artigo tenha ajudado você a aprender como fazer imagens em escala de cinza no WordPress. Você também pode conferir nosso guia sobre como escolher a melhor plataforma de blog e nossas escolhas de especialistas sobre o melhor software de web design.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

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.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

18 ComentáriosDeixe uma resposta

  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

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.