bfi_thumb是一款类似于TimThumb的图片处理php脚本,由于timthumb的安全性问题,很多WordPress主题不再使用这个脚本,bfi_thumb是一款很好的替代产品。它通过扩展WordPress Image Editor class来实现各种图片处理效果,相比timthumb更加安全。
概述
该脚本以WordPress Image Editor class为根基,增加了图片动态缩放、裁切、灰度、上色、反相、透明度等功能。可以对任何本地图片进行处理,也可以通过WordPress默认函数调用,如the_post_thumbnail(),直接对WordPress生成的缩略图进行二次处理。
动态生成的图片存储在wp-content/uploads/bfi_thumb目录下,使用如下代码更改目录@define( BFITHUMB_UPLOAD_DIR, 'other_dir' );
基本用法
首先,引入脚本文件require_once('BFI_Thumb.php');
将图片尺寸缩小到宽度为400$params = array( 'width' => 400 );
echo "";
bfi_thumb直接返回生成的图片的url。
再看,更改透明度$params = array( 'opacity' => 80 ); // 80% opaque
bfi_thumb( "URL-to-image.jpg", $params );
上色$params = array( 'color' => '#ff0000' );
bfi_thumb( "URL-to-image.jpg", $params );
灰度$params = array( 'grayscale' => true );
bfi_thumb( "URL-to-image.jpg", $params );
反相$params = array( 'negate' => true );
bfi_thumb( "URL-to-image.jpg", $params );
同时使用多个参数$params = array( 'width' => 400, 'height' => 300, 'opacity' => 50, 'grayscale' => true, 'colorize' => '#ff0000' );
bfi_thumb( "URL-to-image.jpg", $params );
通过WordPress图片函数调用
对于任何上传到媒体库中的图片,还可以这样调用。
例如,将the_post_thumbnail返回的图片进行缩放和灰度处理,再输出the_post_thumbnail( array( 1024, 400, 'bfi_thumb' => true, 'grayscale' => true ) );
实际处理效果
正片叠底
Photoshop的正片叠底是非常酷的效果,该脚本并不支持,可以自己添加,方法如下。
[download id=54]
打开BFI_Thumb.php,更改如下代码
找到public function colorize($hexColor){...}
在该方法后面添加新的方法public function multiply($hexColor) {
if (function_exists('imagefilter') &&
function_exists('imagesavealpha') &&
function_exists('imagecolorat')) {
$hexColor = preg_replace('#^\##', '', $hexColor);
$r = hexdec (substr ($hexColor, 0, 2));
$g = hexdec (substr ($hexColor, 2, 2));
$b = hexdec (substr ($hexColor, 4, 2));
$imagex = imagesx($this->image);
$imagey = imagesy($this->image);
for ($x = 0; $x
for ($y = 0; $y
$rgb = imagecolorat($this->image, $x, $y);
$TabColors=imagecolorsforindex ( $this->image , $rgb );
$color_r=floor($TabColors['red']*$r/255);
$color_g=floor($TabColors['green']*$g/255);
$color_b=floor($TabColors['blue']*$b/255);
$newcol = imagecolorallocate($this->image, $color_r,$color_g,$color_b);
imagesetpixel($this->image, $x, $y, $newcol);
}
}
//imagesavealpha($this->image, false);
return true;
}
return new WP_Error( 'image_colorize_error', __('Image color change failed.', 'default'), $this->file );
}
找到(isset($color) ? str_pad(preg_replace('#^\##', '', $color), 8, '0', STR_PAD_LEFT) : '00000000') .
在其后添加(isset($multiply) ? str_pad(preg_replace('#^\##', '', $multiply), 8, '0', STR_PAD_LEFT) : '00000000') .
找到if ( isset( $color ) ) {
if ( is_wp_error( $editor->colorize( $color ) ) ) {
return false;
}
}
在其后添加if ( isset( $multiply ) ) {
if ( is_wp_error( $editor->multiply( $multiply ) ) ) {
return false;
}
}
这样就可以调用正片叠底(Multiply)功能了,如$params = array( 'width' => 300, 'multiply' => '#ff0000' );