If I have a YouTube video URL, is there any way to use PHP and cURL to get the associated thumbnail from the YouTube API?
Use img.youtube.com/vi/YouTubeID/ImageFormat.jpg
Here image formats are different like default, hqdefault, maxresdefault.
If all you want to do is search YouTube and get associated properties:
Get a public API -- This link gives a good direction
Use below query string. The search query (denoted by q=) in the URL string is stackoverflow for example purposes. YouTube will then send you back a JSON reply where you can then parse for Thumbnail, Snippet, Author, etc.
https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&maxResults=50&q=stackoverflow&key=YOUR_API_KEY_HERE
Use:
https://www.googleapis.com/youtube/v3/videoCategories?part=snippet,id&maxResults=100®ionCode=us&key=**Your YouTube ID**
Above is the link. Using that, you can find the YouTube characteristics of videos. After finding characteristics, you can get videos of the selected category. After then you can find selected video images using Asaph's answer.
Try the above approach and you can parse everything from the YouTube API.
I made a function to only fetch existing images from YouTube
function youtube_image($id) {
$resolution = array (
'maxresdefault',
'sddefault',
'mqdefault',
'hqdefault',
'default'
);
for ($x = 0; $x < sizeof($resolution); $x++) {
$url = '//img.youtube.com/vi/' . $id . '/' . $resolution[$x] . '.jpg';
if (get_headers($url)[0] == 'HTTP/1.0 200 OK') {
break;
}
}
return $url;
}
If you want to get rid of the "black bars" and do it like YouTube does it, you can use:
https://i.ytimg.com/vi_webp/<video id>/mqdefault.webp
And if you can't use the .webp
file extension you can do it like this:
https://i.ytimg.com/vi/<video id>/mqdefault.jpg
Also, if you need the unscaled version, use maxresdefault
instead of mqdefault
.
Note: I'm not sure about the aspect ratio if you're planning to use maxresdefault
.
I found this nifty tool that allows you to create the image with the YouTube play button placed over the image: