【问题标题】:Converting image to grayscale in WordPress using PHP使用 PHP 在 WordPress 中将图像转换为灰度
【发布时间】:2019-11-28 18:33:39
【问题描述】:

我正在尝试自定义一个 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' ) ) );
    }
}

【问题讨论】:

  • 您遇到了什么错误?什么不起作用?尝试缩小您的问题范围,让我们知道您发现了什么。
  • 好的,知道了。我刚刚打开调试。错误是“imagefilter() 期望参数 1 是资源,在 .... 中给出的对象”
  • @DavidCulbreth 我通过这样做摆脱了错误,$image_res = imagecreatefromjpeg($image_path);图像过滤器($image_res,IMG_FILTER_GRAYSCALE); imagejpeg($image_res);但是现在最终图像确实出现在网页上,并且没有任何错误。不在 debug.log 或网页中。
  • @DavidCulbreth 当我删除 imagejpeg($image_res);它恢复正常,如图所示,prnt.sc/ohnmb3 但图像不是灰度的。

标签: php wordpress image-processing


【解决方案1】:

问题是这行代码:

$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。

【讨论】:

  • 非常感谢。当我把你的代码放在最后而不是在 $image = wp_get_image_editor( $image_path );
猜你喜欢
  • 1970-01-01
  • 2010-11-20
  • 2021-06-06
  • 2018-12-19
  • 1970-01-01
相关资源
最近更新 更多