RGBA format HEX into RGB format HEX? PHP

前端 未结 4 709
攒了一身酷
攒了一身酷 2021-01-16 18:02

I want to convert back and forth between RGBA-formated HEX colors (like0xFF0000FF) and RGB-formated HEX colors (like 0xFF0000) in PHP.

How

相关标签:
4条回答
  • 2021-01-16 18:54

    These two functions will do what you need:

    function rgbaToRgb ($rgba) {
        return substr($rgba, 0, -2);
    }
    
    function rgbToRgba ($rgb) {
        return $rgb . "FF";
    }
    

    The first one simply removes the last two characters, whilst the second one simply appends FF.

    0 讨论(0)
  • 2021-01-16 18:54

    As Frank mentioned, you can simply strip the last 2 digits.

    The hex format is 3 pairs of numbers, the first pair Red value, the next is Green, and the next is blue. If you add another pair, it's assumed to be the alpha value.

    0 讨论(0)
  • 2021-01-16 19:07

    How about these:

    function rgbaToRgb ($rgba, $blend = 0xFFFFFF) {
        return (($rgba >> 8)*($rgba & 0xFF)/0xFF) * ($blend / 0xFFFFFF);
    }
    
    function rgbToRgba ($rgb) {
        return ($rgb << 8) | 0xFF;
    }
    

    $blend in the first is effectively a background color to blend with.

    Edit: fix due to not enough space in ints ruining RGBA. RGBA is now handled as a four part array. RGB remains a number.:

    function rgbaToRgb ($rgba, $blend = 0xFFFFFF) {
    $rbg = array($rgba[0] * $rgba[3]/0xFF + ($blend>>16) * (0xFF-$rgba[3])/0xFF, $rgba[1] * $rgba[3]/0xFF + (($blend>>8)&0xFF)*(0xFF-$rgba[3])/0xFF, $rgba[2] * $rgba[3]/0xFF + ($blend&0xFF) * (0xFF-$rgba[3])/0xFF);
    return ($rbg[0]<<16) + ($rbg[1]<<8) + $rbg[2];
    }
    
    function rgbToRgba ($rgb) {
        return array($rgb >> 16, ($rgb >> 8) & 0xFF, $rgb & 0xFF, 0xFF);
    }
    
    0 讨论(0)
  • 2021-01-16 19:07

    RGBA -> RGB should be simple, as it's just cutting off the last two digits. The other direction is impossible, as alpha information isn't encoded in RGB.

    0 讨论(0)
提交回复
热议问题