Home >Backend Development >PHP Tutorial >PHP怎么把一张图片透明化

PHP怎么把一张图片透明化

PHPz
PHPzOriginal
2016-06-06 20:51:182078browse

PHP怎么把一张图片透明化

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));                
            }
        }
    }
}

方法:

/**
 * Created by PhpStorm.
 * User: shellus
 * Date: 2016-12-01
 * Time: 23:12
 */
require &#39;vendor/autoload.php&#39;;
// import the Intervention Image Manager Class
use Intervention\Image\ImageManager;
// create an image manager instance with favored driver
$manager = new ImageManager(array(&#39;driver&#39; => &#39;gd&#39;));
$img =  $manager->make(&#39;1.jpg&#39;);
for ($y = 0; $y < $img->height(); $y++)
{
    for ($x = 0; $x < $img->width(); $x++)
    {
        $c = $img -> pickColor($x, $y, &#39;array&#39;);
        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);

更多相关技术文章,请访问PHP中文网

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn