dechex not showing first two zeros (rgb to hex)

Discussion in 'PHP' started by abyse, Sep 9, 2017.

  1. #1
    Hi, i'm newbie in php and i got a little problem.

    I use this php script to get the rgb color from a jpg file...

    
    <?php
    $image=imagecreatefromjpeg('thumbs/dark-blue-material-texture.jpg');
    $thumb=imagecreatetruecolor(1,1); imagecopyresampled($thumb,$image,0,0,0,0,1,1,imagesx($image),imagesy($image));
    $mainColor=(dechex(imagecolorat($thumb,0,0)));
    echo $mainColor;
    ?>
    
    PHP:

    the script for the image "dark-blue-material-texture.jpg" returns this hex color: 176e from (rgb(0, 23, 110))
    but the correct hex would be: 00176e

    I see that the script not showing the first two zeros, is there a way to showing all the zeros when using dechex?
     
    abyse, Sep 9, 2017 IP
  2. RoseHosting

    RoseHosting Well-Known Member

    Messages:
    230
    Likes Received:
    11
    Best Answers:
    11
    Trophy Points:
    138
    #2
    RoseHosting, Sep 12, 2017 IP
    abyse likes this.
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    str_pad is your friend.

    $mainColor = str_pad(dechex(imagecolorat($thumb, 0, 0)), 6, '0', STR_PAD_LEFT);
    Code (markup):
    @RoseHosting -- REALLY? floating point math doing subtraction's job?
     
    deathshadow, Sep 14, 2017 IP
    abyse likes this.
  4. abyse

    abyse Notable Member

    Messages:
    346
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    245
    #4
    abyse, Sep 15, 2017 IP
  5. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #5
    And remember, the value of 00176E and the value of 176E are exactly the same. Break it into sets of 2 digits starting at the right end.
     
    Rukbat, Sep 22, 2017 IP