Search code examples
javascriptjqueryimagecolorspixel

Get first pixel's color of an image ( JS / jQuery )


I have - for example - this pic:

var imgSrc = "http://scottkleinberg.com/wp-content/uploads/2012/10/icon-512x512.png";

And i need only variable with RGB or RGBA or HEX color on first position pixel (0,0):

var color = getFirstPixelColor( imgSrc ); // Should return #AAE8FE or 170,323,254 or 170,323,254,1

Solution

  • I have a resuln, but only with PHP:

    $imgObject = imagecreatefrompng('http://scottkleinberg.com/wp-content/uploads/2012/10/icon-512x512.png');
    $fillColor = imagecolorat($imgObject, 0, 0);
    
     $rgba = array(
        ($fillColor >> 16) & 0xFF,
        ($fillColor >> 8) & 0xFF,
         $fillColor & 0xFF,
    );
    
    print_r($rgba);
    

    When is the image JPG or JPEG format:

    $imgObject = imagecreatefromjpeg('http://scottkleinberg.com/wp-content/uploads/2012/10/icon-512x512.png');
    $fillColor = imagecolorat($imgObject, 0, 0);
    
     $rgba = array(
        ($fillColor >> 16) & 0xFF,
        ($fillColor >> 8) & 0xFF,
         $fillColor & 0xFF,
    );
    
    print_r($rgba);