Undrar du om det fanns ett sätt att automatiskt gråskala images i WordPress när du uploadar dem?
Vanligtvis behöver du ett fotoredigeringsverktyg för att ändra dina images till gråskala. Detta kan dock vara tidskrävande eftersom du måste edit varje enskild image innan du uploadar den till din website.
I den här artikeln visar vi dig hur du gråskalar images i WordPress när du uppladdar dem till din site.
När ska du använda gråskaliga images i WordPress?
Grayscale images innehåller endast information om ljusmängden i bilden. Färgerna i images visar olika nyanser av grått, som varierar mellan svart och vitt.
I vissa situationer kan det vara bra att använda gråskaliga images på din WordPress website. Till exempel kan du använda den för att förbättra läsbarheten av de objekt som visas i imagen.
Å andra sidan används gråskaliga images ofta för att Behandlas image på grund av deras lilla storlek. Det allow utvecklare att run komplexa operationer på kortare tid.
Med detta sagt, låt oss se hur du kan ändra dina images till gråskala i WordPress när du uploadar dem.
Graysacling Images vid uppladdning i WordPress
När det gäller att lägga till images i WordPress måste du editera dem innan du uppladdar dem med ett fotoredigeringsprogram som gillar Photoshop och konvertera färgade bilder till gråskala.
Om du har hundratals eller tusentals images att uploada kan det ta mycket tid att editera varje bild manuellt.
Du kan dock automatiskt förvandla dem till gråskaliga images vid upload. För att börja, allt du behöver göra är att add to följande kod till ditt temas functions.php-fil:
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;
}
Ett enkelt sätt att lägga till kod i temafiler är att använda pluginet WPCode för WordPress.
Det är det bästa code snippets pluginet som hjälper dig att run code snippets utan att du manuellt behöver editera ditt temas function.php-fil. På så sätt behöver du inte oroa dig för att förstöra din site.
Först måste du downloada och installera det gratis pluginet WPCode på din site. Om du behöver hjälp, vänligen följ vår guide om hur du installerar ett plugin för WordPress.
Note: Den gratis versionen av WPCode erbjuder allt du behöver för att enkelt add to custom code i WordPress. För mer avancerade funktioner som gillar ett privat moln snippet bibliotek, tidsinställda snippets, conversion Pixels, och mer, kan du uppgradera till WPCode Pro.
Efter aktivering kan du head to Code Snippets ” + Add New från din WordPress dashboard.
Navigera sedan till alternativet ”Add Your Custom Code (New Snippet)” och klicka på knappen ”Use snippet”.
Därefter går du vidare och anger ett namn för ditt snippet och klistrar in koden ovan i ”Code Preview” -området.
Du måste också välja ”PHP Snippet” som code type från dropdown-listan till höger.
När du har enter koden kan du rulla ner till ”Insertion” section.
Här kan du låta alternativet ”Auto Insert” vara valt. Detta kommer automatiskt att infoga och exekvera koden åt you.
Slutligen går du tillbaka högst upp på vyn och togglar omkopplaren från ”Inaktiverad” till ”Aktiv” och klickar på knappen ”Save Snippet”.
Därefter kan du testa koden genom att editera eller lägga till en new page. När du är i WordPress editor, gå vidare, click the ”+” button and add a Image block.
Nu kan du uploada vilken image som helst på din WordPress blogg och den konverteras automatiskt till en gråskalebild.
Vi hoppas att den här artikeln hjälpte dig att lära dig hur du gråskalar images i WordPress. You can also check out our guide on how to choose the best blogging platform and our expert picks of the best web design software.
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.
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!
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
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;
}
Kim says
Will this change all pictures in word press to grayscale or only newly updates ones?
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;
}
endul says
how to change, result filter image to specific folder/directory
geertvdheide says
One addition: I’ve added a few lines to get around the issue of having two images with the same file name, caused by having two add_image_size calls with the same size. The additional code was found here:
http://bavotasan.com/2011/create-black-white-thumbnail-wordpress/
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:
Mike Logan says
Excellent idea, almost 10 years later this is still handy.
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!
frankiegershwin says
@Otto42 Thanks for offering. I will.
Otto42 says
@frankiegershwin bummer! Feel free to email me directly for code help. otto@wordpress.org
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
Otto42 says
@frankiegershwin Lemme know if you need help. I added a way to do sepia tones too in my comments on the original post: http://t.co/avDNNEX
rodhk says
@rodriguezhernan vaya idiotez de truco…. madremua tocar el codigo para eso
wpbeginner says
@Otto Thanks for the comment Otto. Updated the post as well
Otto says
Note that people should change ”themename” to be the name of their theme instead.