首页 > 开发 > php > 正文

PHP 怎么去掉一张图片里的一些颜色,让其变成透明?

2017-09-06 15:06:49  来源:网友分享

把一张图片(根据指定的RGB颜色范围)透明化。但是实际处理当中,下面的代码值移除了白色,请教是怎么回事?

$o_pic = '1.jpg';//要处理的色阶起始值$begin_r = 215;$begin_g = 215;$begin_b = 215;list($src_w,$src_h,$src_type) = getimagesize($o_pic);// 获取原图像信息$file_ext = get_ext($o_pic);//获取扩展名$target_im = imagecreatetruecolor($src_w,$src_h);//新图if($file_ext == 'jpg') //转换JPG 开始{    $src_im = ImageCreateFromJPEG($o_pic);          imagecopymerge($target_im,$src_im,0,0,0,0,$src_w,$src_h,100);    for($x = 0; $x < $src_w; $x++)    {        for($y = 0; $y < $src_h; $y++)        {            $rgb = imagecolorat($src_im, $x, $y);            $r = ($rgb >> 16) & 0xFF;            $g = ($rgb >> 8) & 0xFF;            $b = $rgb & 0xFF;            if($r > $begin_r && $g > $begin_g && $b > $begin_b ){                   imagecolortransparent($target_im, imagecolorallocate($target_im,$r, $g, $b));                            }        }    }}

解决方案

时隔4年,我来贡献一个面向对象的。哈哈

/** * Created by PhpStorm. * User: shellus * Date: 2016-12-01 * Time: 23:12 */require 'vendor/autoload.php';// import the Intervention Image Manager Classuse Intervention\Image\ImageManager;// create an image manager instance with favored driver$manager = new ImageManager(array('driver' => 'gd'));$img =  $manager->make('1.jpg');for ($y = 0; $y < $img->height(); $y++){    for ($x = 0; $x < $img->width(); $x++)    {        $c = $img -> pickColor($x, $y, 'array');        if(abs($c[0] - 205) < 50  && abs($c[1] - 223) < 50 && abs($c[2] - 211) < 50 ){            $c[0] = $c[1] = $c[2] = 255;            $img -> pixel($c, $x, $y);        }    }}$img -> save();