Search code examples
phpgdimagefilter

Can I pass variables to PHP GD imagefilter?


I know the imagefilter function expects a long but is there a way to cast a variable to a long or am I forced to simply create separate functions for each filter. My thought is this:

public function ImgFilter($filter, $arg1=null, $arg2=null){
    $this->lazyLoad();
    if($this->_cache_skip) return;
    if(isset($this->_image_resource)){
        imagefilter($this->_image_resource, $filter);
    }
}

It's complaining about my $filter variable. For this example my $filter value is: IMG_FILTER_GRAYSCALE

Is this possible?


Solution

  • Provided:

    $filter = "IMG_FILTER_GRAYSCALE"
    

    You should be able to use the function constant:

    imagefilter($this->_image_resource, constant($filter));
    

    However note that the following will also work just fine:

    $filter = IMG_FILTER_GRAYSCALE
    imagefilter($this->_image_resource, $filter);
    

    You can pass around the constant as an argument without a problem if you need to do so. The former is only useful if you really need the constant name to be dynamic.