图片处理 - PHP 怎么去掉一张图片里的一些颜色,让其变成透明?
ringa_lee
ringa_lee 2017-04-10 14:22:32
[PHP讨论组]

把一张图片(根据指定的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));                
            }
        }
    }

}
ringa_lee
ringa_lee

ringa_lee

全部回复(2)
ringa_lee

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

/**
 * Created by PhpStorm.
 * User: shellus
 * Date: 2016-12-01
 * Time: 23:12
 */


require 'vendor/autoload.php';
// import the Intervention Image Manager Class
use 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();
怪我咯

请不要用jpg,因为jpg不支持透明所以变白了,用imagecreatetruecolor或是imagecreatefrompng

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号