图片转png透明背景图 图片转png透明背景图

图片转png透明背景图

/**
 * 图片转png透明背景图
 * 
 * 将原图颜色在阈值一下的像素都改为白色,创建一张等大的白色为透明色的空白图,将原图复制到新图上面,返回图片资源
 *
 * @param [string] $img 图片地址
 * @param integer $threshold(0, 255) 图片背景颜色阈值
 * @return resource gd图片资源
 */
function imgBg2Transparent($img, $threshold = 128) {
    list($w, $h, $type) = getimagesize($img);
    switch ($type) {
        case 1:
            $src_im = imagecreatefromgif($img);
            break;
        case 2:
            $src_im = imagecreatefromjpeg($img);
            break;
        case 3:
            $src_im = imagecreatefrompng($img);
            break;
    }
    $src_white = imagecolorallocate($src_im, 255, 255, 255); //返回图片白色标识符
    for ($x = 0; $x < $src_w; $x++) {
        for ($y = 0; $y < $src_h; $y++) {
            // 获取对应像素的rgb值
            $rgb = imagecolorat($src_im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            // 如果小于阈值认为是背景,替换成白色
            if($r >= $threshold && $g >= $threshold && $b >= $threshold) imagefill($src_im, $x, $y, $src_white); 
        }
    }
    $target_im = imagecreatetruecolor($w, $h); //创建一张等大的空白图
    $tag_white = imagecolorallocate($target_im, 255, 255, 255); //返回图片白色标识符
    imagefill($target_im, 0, 0, $tag_white); //将空白图的背景填充为白色
    imagecolortransparent($target_im, $tag_white); //将白色定义为透明色
    imagecopy($target_im, $src_im, 0, 0, 0, 0, $w, $h);
    return $target_im;
}
$im = imgBg2Transparent("123.jpg");
imagepng($im, "zhuan.png"); 

评论 0

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论