wordpress图像大小_如何在WordPress中对图像进行灰度处理

wordpress图像大小

Did you ever wonder if there was a way to automatically grayscale images in WordPress when you upload them? Well the wondering time is over. In this article, we will show you how you can use some simple PHP image manipulation tools and WordPress functions to automatically grayscale images upon upload. You can use grayscale images for hover, sliders, gallery, or anything else you like.

您是否曾经想过在上载WordPress时是否有一种自动灰度图像的方法? 好吧,想知道的时间已经过去了。 在本文中,我们将向您展示如何使用一些简单PHP图像处理工具和WordPress函数在上传时自动对图像进行灰度处理。 您可以将灰度图像用于悬停,滑块,图库或其他任何您喜欢的图像。

Grayscale Images in WordPress

First thing you need to do is open your theme’s functions.php file and add the following code:

您需要做的第一件事是打开主题的functions.php文件并添加以下代码:

add_action('after_setup_theme','themename_bw_size');
function themename_bw_size() {
	add_image_size('themename-bw-image', 100, 100, true);
}

The code above simply adds an additional image size for the uploader. The size is set to 100 x 100px with hard cropping. You may change the dimensions to fit your needs. Once you have done that, you need to add the following code:

上面的代码只是为上传器添加了额外的图片大小。 硬裁剪时,尺寸设置为100 x 100像素。 您可以更改尺寸以适合您的需求。 完成此操作后,需要添加以下代码:


add_filter('wp_generate_attachment_metadata','themename_bw_filter');
function themename_bw_filter($meta) {
	$file = wp_upload_dir();
	$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;
}

The code above pretty much tells the uploader to create an extra size of the image you uploaded. Crop it to the size you have specified in the previous step. Then apply the image filter: Grayscale.

上面的代码几乎告诉上传者为您上传的图像创建额外的尺寸。 将其裁剪为上一步中指定的尺寸。 然后应用图像滤镜:灰度。

If you were doing this for your post thumbnails, then you can display it like this in your theme:

如果您要对帖子缩略图进行此操作,则可以在主题中将其显示为:

<?php the_post_thumbnail( 'themename-bw-image' ); ?>

If you want to do this for a specific attachment, then you can use wp_get_attachment_image function.

如果要对特定附件执行此操作,则可以使用wp_get_attachment_image函数。

Note: You should change themename to your theme’s name.

注意:您应该将主题名称更改为主题名称。

All credits for this awesome trick goes to Otto.

这个绝妙的绝招归功于奥托

翻译自: https://www.wpbeginner.com/wp-tutorials/how-to-grayscale-images-in-wordpress/

wordpress图像大小

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值