php 16进制颜色代码转换为rgba,rgb格式

<?php
   $rgb = hex2rgba'#FFFFFF', false, true);
   echo 'rgb: '.$rgb[0].',';
   echo $rgb[1].',';
   echo $rgb[2].'<br>';
   
   $rgba = hex2rgba"FFFFFF");
   echo 'rgba: '.$rgba;
   
   function hex2rgba$color, $opacity = false, $raw = false) {
        $default = 'rgb0,0,0)';
        //Return default if no color provided
        ifempty$color))
              return $default; 
        //Sanitize $color if "#" is provided 
        if $color[0] == '#' ) {
            $color = substr $color, 1 );
        }
        //Check if color has 6 or 3 characters and get values
        if strlen$color) == 6) {
                $hex = array $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
        } elseif  strlen $color ) == 3 ) {
                $hex = array $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
        } else {
                return $default;
        }
 
        //Convert hexadec to rgb
        $rgb =  array_map'hexdec', $hex);
 
        if$raw){
            if$opacity){
                ifabs$opacity) > 1) $opacity = 1.0;
                array_push$rgb, $opacity);
            }
            $output = $rgb;
        }else{
            //Check if opacity is setrgba or rgb)
            if$opacity){
                ifabs$opacity) > 1)
                    $opacity = 1.0;
                $output = 'rgba'.implode",",$rgb).','.$opacity.')';
            } else {
                $output = 'rgb'.implode",",$rgb).')';
            }
        }
 
        //Return rgba) color string
        return $output;
    }

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注