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

Jak wyświetlać obrazki w skali szarości w WordPressie

Uwaga redakcyjna: Otrzymujemy prowizję z linków partnerskich na WPBeginner. Prowizje nie mają wpływu na opinie i oceny naszych redaktorów. Dowiedz się więcej o Proces redakcyjny.

Zastanawiasz się, czy istnieje sposób na automatyczne skalowanie szarości obrazków w WordPressie podczas ich przesyłania?

Zazwyczaj do zmiany twoich obrazków na skalę szarości potrzebne jest narzędzie do edycji zdjęć. Może to być jednak czasochłonne, ponieważ musisz edytować każdy pojedynczy obrazek przed przesłaniem go do witryny internetowej.

W tym artykule pokażemy, jak przesłać obrazek w skali szarości do witryny WordPress.

Greyscale Images in WordPress

Kiedy należy używać obrazków w skali szarości w WordPress?

Obrazki w skali szarości zawierają tylko informacje o ilości światła w obrazku. Kolory obrazków przedstawiają różne odcienie szarości, wahające się między czernią a bielą.

W pewnych sytuacjach używanie obrazków w skali szarości może być korzystne dla twojej witryny internetowej WordPress. Na przykład, można go użyć do poprawy czytelności obiektów przedstawionych na obrazku.

Z drugiej strony, obrazy w skali szarości są powszechnie używane do przetwarzania obrazków ze względu na ich niewielki rozmiar. Pozwala to programistom na wykonywanie złożonych operacji w krótszym czasie.

To powiedziawszy, zobaczmy, jak możesz zmienić twoje obrazki na skalę szarości w WordPressie podczas ich przesyłania.

Graysacling obrazków przy przesyłaniu w WordPressie

Jeśli chodzi o dodawanie obrazków w WordPressie, przed ich załadowaniem należałoby je edytować za pomocą oprogramowania do edycji zdjęć, takiego jak Photoshop, i przekonwertować kolorowe obrazki na skalę szarości.

Jeśli masz setki lub tysiące obrazków do przesłania, ręczna edycja każdego z nich może zająć dużo czasu.

Można jednak automatycznie przekształcić je w obrazki w skali szarości podczas przesyłania. Aby rozpocząć, wystarczy dodać następujący kod do pliku functions.php twojego motywu:

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;
}

Prostym sposobem na dodanie kodu do plików motywu jest użycie wtyczki WPCode dla WordPressa.

Jest to najlepsza wtyczka do fragmentów kodu, która pomaga uruchamiać fragmenty kodu bez konieczności ręcznej edycji pliku function.php twojego motywu. Dzięki temu nie musisz się martwić, że zepsujesz swoją witrynę.

WPCode

Najpierw musisz pobrać i zainstalować darmową wtyczkę WPCode na twojej witrynie. Jeśli potrzebujesz pomocy, skorzystaj z naszego przewodnika na temat instalacji wtyczki WordPress.

Uwaga: Darmowa wersja WPCode oferuje wszystko, czego potrzebujesz, aby łatwo dodać własny kod w WordPress. Aby uzyskać bardziej zaawansowane funkcje, takie jak prywatna biblioteka fragmentów kodu w chmurze, zaplanowane fragmenty kodu, piksele konwersji i inne, możesz uaktualnić do WPCode Pro.

Po włączaniu, możesz udać się do Code Snippets ” + Add New z twojego kokpitu WordPress.

Następnie przejdź do opcji „Add Your Custom Code (New Snippet)” i kliknij przycisk „Use snippet”.

Add a new custom code snippet in WPCode

Następnie wpisz nazwę twojego fragmentu kodu i wklej powyższy kod w obszarze „Podgląd kodu”.

Należy również wybrać „Fragment kodu PHP” jako rodzaj kodu z rozwijanej listy po prawej stronie.

Add code snippet for grayscale images

Po wpiszeniu kodu można przewinąć w dół do sekcji „Wybierak”.

Tutaj możesz pozostawić zaznaczoną opcję „Automatyczne wstawienie”. Spowoduje to automatyczne wstawienie i wykonanie kodu.

Insertion methods for snippets in WPCode

Na koniec wróć do górnej części ekranu i przełącz przełącznik z „Nieaktywny” na „Aktywny” i kliknij przycisk „Zapisz fragment kodu”.

Save and activate your custom code snippet

Następnie możesz przetestować kod, edytując lub dodając nową stronę. Będąc w edytorze WordPress, kliknij przycisk „+” i dodaj blok z obrazkiem.

Możesz teraz przesłać dowolny obrazek na swojego bloga WordPress, a zostanie on automatycznie przekonwertowany na obraz w skali szarości.

Convert images to grayscale on upload

Mamy nadzieję, że ten artykuł pomógł ci nauczyć się skalowania szarości obrazków w WordPress. Zachęcamy również do zapoznania się z naszym przewodnikiem na temat wyboru najlepszej platformy do prowadzenia blogów oraz z naszą ekspercką listą najlepszych programów do projektowania stron internetowych.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Ujawnienie: Nasze treści są wspierane przez czytelników. Oznacza to, że jeśli klikniesz na niektóre z naszych linków, możemy otrzymać prowizję. Zobacz jak WPBeginner jest finansowany, dlaczego to ma znaczenie i jak możesz nas wspierać. Oto nasz proces redakcyjny.

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.

Najlepszy zestaw narzędzi WordPress

Uzyskaj BEZPŁATNY dostęp do naszego zestawu narzędzi - zbiór produktów i zasobów związanych z WordPressem, które każdy profesjonalista powinien mieć!

Reader Interactions

18 komentarzyZostaw odpowiedź

  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

Zostaw odpowiedź

Dziękujemy za pozostawienie komentarza. Pamiętaj, że wszystkie komentarze są moderowane zgodnie z naszymi polityka komentarzy, a Twój adres e-mail NIE zostanie opublikowany. NIE używaj słów kluczowych w polu nazwy. Przeprowadźmy osobistą i konstruktywną rozmowę.