用php把图片不透明改成透明

问题描述 投票:0回答:1

我想问一下,如何让第一张图片成为第二张图片? 从某种意义上说,背景的第一张图片不是透明的,我会在图片上变成透明的,变得像第二张图片吗? 你是如何用 php 做的? 我真的不知道

图 1- enter image description here 图片 2- enter image description here

请帮忙!

php codeigniter-3
1个回答
0
投票

如果您只有黑白图像,则可以打破所有像素中的白色。

<?php
  $url = "IUWBw.jpg";
  $image = imagecreatefromjpeg($url);//get your image
  //get size
  $width = imagesx($image);
  $height = imagesy($image);
  //create new image
  $out = ImageCreateTrueColor($width,$height);

  //configuration for make alpha color
  imagealphablending($out,false);
  imagesavealpha($out, true);

  for($x = $width-1;$x>=0;$x--){
    for($y = $height-1;$y>=0;$y--){
        $rgb = imagecolorat($image,$x,$y);//get pixel color of original image
        $r =   $rgb >> 16;
        $g =   ord(chr($rgb >> 8)); 
        $b =   ord(chr($rgb));
        if( $rgb != 0 ){ //if pixel is not black
            //if red is the low color
            if($r<$g && $r < $b){
                $alpha =  ($r / 2);
                $g-=$r;$b-=$r; $r=0;
            }
            //if green is the low color
            if($g<$r && $g < $b){
                $alpha =  ($g / 2);
                 $r-=$g;$b-=$g;$g=0;
            }
            //if blue is the low color
            if($b<$r && $b < $g){
                 $alpha =($b / 2);
                $r-=$b; $g-=$b;$b=0;  
            }
            //if we all have equal value
            if($b == $r && $b == $g){
                 $alpha = ($b / 2);
                $r-=$b; $g-=$b;$b=0;  
            }

            $color = $alpha << 24 | $r << 16 | $g << 8 | $b;

            imagesetpixel($out,$x,$y,$color);

        }else{//else is black just write 
                imagesetpixel($out,$x,$y,$rgb);
        }
    }
  }


    $urlout = preg_replace("#(.+).jpe?g#i","$1.png",$url);

    imagepng($out,$urlout);
    echo "image writeted: ".$urlout;
    imagedestroy($out);
    imagedestroy($image);

?>

此代码查找一个像素的低值并将其从另一个值中减去。

示例:一个像素,因此值为 r:255 g:226 b:255。
他将其转换为 r: 29 g: 0 b: 29;

现在像素没有白色值,剩下的就是放置适当的 alpha。 'g' 的值在转换前除以 2。除以 2,因为 alpha 支持值 127 而不是 255。 a = g / 2 = 226/2 = 113。

此代码也适用于彩色图像,但整个图像将是半透明的。除了黑色。

© www.soinside.com 2019 - 2024. All rights reserved.