我正在尝试自定义一个WordPress插件,该插件具有一个功能,希望添加将彩色图像转换为灰度的动作。我了解到imagefilter($image, IMG_FILTER_GRAYSCALE)
可以解决问题。但我似乎无法使其正常工作。
public function stream_photo( $image_path, $src, $key, $user_id, $coord, $crop ) {
$image = wp_get_image_editor( $image_path ); // Return an implementation that extends WP_Image_Editor
//DEBUG
imagefilter($image, IMG_FILTER_GRAYSCALE);
$quality = UM()->options()->get( 'image_compression' );
if ( ! is_wp_error( $image ) ) {
if ( ! empty( $crop ) ) {
if( ! is_array( $crop ) ) {
$crop = explode(",", $crop );
}
$src_x = $crop[0];
$src_y = $crop[1];
$src_w = $crop[2];
$src_h = $crop[3];
$image->crop( $src_x, $src_y, $src_w, $src_h );
$max_w = UM()->options()->get('image_max_width');
if ( $src_w > $max_w ) {
$image->resize( $max_w, $src_h );
}
}
//DEBUG
//echo "Image path is: " . $image_path;
//$image = wp_load_image($image_path);
//imagefilter($image_path, IMG_FILTER_GRAYSCALE);
$image->save( $image_path );
//DEBUG
//imagefilter($image, IMG_FILTER_GRAYSCALE);
$image->set_quality( $quality );
//DEBUG
//echo "Image path is: " . $image_path;
//$image2 = wp_load_image($image_path);
//imagefilter($image2, IMG_FILTER_GRAYSCALE);
} else {
wp_send_json_error( esc_js( __( "Unable to crop stream image file: {$image_path}", 'ultimate-member' ) ) );
}
}
答案 0 :(得分:0)
问题是这行代码:
$image = wp_get_image_editor( $image_path ); // Return an implementation that extends WP_Image_Editor
//DEBUG
imagefilter($image, IMG_FILTER_GRAYSCALE);
wp_get_image_editor返回一个WP_Image_Editor对象,但是imagefilter仅需要“图像资源”。下面的更改应该起作用。
$image = wp_get_image_editor( $image_path ); // Return an implementation that extends WP_Image_Editor
$im = imagecreatefrompng($image_path);
if($im && imagefilter($im, IMG_FILTER_GRAYSCALE)){
// Convert to grayscale
imagefilter(imagecreatefrompng($image_path), IMG_FILTER_GRAYSCALE);
// Save image
imagepng($im, $image_path);
imagedestroy($im);
}
这是针对PNG的,如果您要捕获所有图像扩展名而不是仅捕获PNG。