Papa De Beau
Papa De Beau

Reputation: 3828

Facebook graph get profile picture image type

I am trying to duplicate and work with images from Facebook profiles. I can get the images just fine. The majority of them are 'jpgs' however, some of them are 'pngs' and even a few are 'gifs'. There may be others that I don't know about.

My issue. I need to find out what type of image they are before I work with them.

The below code works to get the image and with json I get the url... but the last line of code will not work unless I have the right image type.

$json = file_get_contents("http://graph.facebook.com/$user[id]/picture?width=512&height=512&redirect=false");

$decoded = json_decode($json,true);
$url = $decoded['data']['url'];



/// This line will only work if the image is a jpeg or it throws an error. 
$source= imagecreatefromjpeg("$url");

Thank you for your help.

Upvotes: 0

Views: 173

Answers (1)

The Gaming Hideout
The Gaming Hideout

Reputation: 584

Grabbed from Create Image From Url Any File Type

$jpeg_image = imagecreatefromfile( 'photo.jpeg' );
$gif_image = imagecreatefromfile( 'clipart.gif' );
$png_image = imagecreatefromfile( 'transparent_checkerboard.PnG' );
$another_jpeg = imagecreatefromfile( 'picture.JPG' );
// This requires you to remove or rewrite file_exists check:
$jpeg_image = imagecreatefromfile( 'http://example.net/photo.jpeg' );
// SEE BELOW HO TO DO IT WHEN http:// ARGS IS NEEDED:
$jpeg_image = imagecreatefromfile( 'http://example.net/photo.jpeg?foo=hello&bar=world' );

function imagecreatefromfile( $filename ) {
    if (!file_exists($filename)) {
        throw new InvalidArgumentException('File "'.$filename.'" not found.');
    }
    switch ( strtolower( pathinfo( $filename, PATHINFO_EXTENSION ))) {
        case 'jpeg':
        case 'jpg':
            return imagecreatefromjpeg($filename);
        break;

        case 'png':
            return imagecreatefrompng($filename);
        break;

        case 'gif':
            return imagecreatefromgif($filename);
        break;

        default:
            throw new InvalidArgumentException('File "'.$filename.'" is not valid jpg, png or gif image.');
        break;
    }
}

Upvotes: 1

Related Questions