2775

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?

stvar
  • 6,551
  • 2
  • 13
  • 28
CodeOverload
  • 47,274
  • 54
  • 131
  • 219
  • 1
    Here are some PHP functions I created to get the best thumbnail available from the URL method w/o pinging the API, based off of the many good answers on this page: https://gist.github.com/squarecandy/30ec9f6779c0e8cdf12e337c665d96c5 – squarecandy May 09 '18 at 18:38
  • From now on you need to use it to extract thumbnail image from YouTube video ID https://img.youtube.com/vi/{VIDEO_ID}/maxresdefault.jpg – Md. Suhel Arman Khan May 23 '23 at 12:43

31 Answers31

5323

Each YouTube video has four generated images. They are predictably formatted as follows:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg

The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (i.e., one of 1.jpg, 2.jpg, 3.jpg) is:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

For the high quality version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a URL similar to the HQ:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

For the standard definition version of the thumbnail, use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

For the maximum resolution version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example URLs above.

Alternatively, you can use the YouTube Data API (v3) to get thumbnail images.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Asaph
  • 159,146
  • 25
  • 197
  • 199
  • 55
    Just in case anyone else makes this dumb mistake - you can't use `http://www.img.youtube.com`, only `http://img.youtube.com` – Ciaran Phillips Nov 05 '13 at 15:04
  • 1
    @KeyLimePiePhotonAndroid, I think queries about playlists would work better as a separate question. – TRiG Nov 27 '13 at 15:43
  • 2
    Additionally, you can use these hostnames `i.ytimg.com`, `i1.ytimg.com`, `i2.ytimg.com`, `i3.ytimg.com`, `i4.ytimg.com` or `s.ytimg.com`. – Modder Sep 23 '14 at 10:51
  • 1
    This is useful as I am trying to eliminate "still picture" videos from my search results. If thumbnails 2 and 3 both exist and are identical it's a very strong likelihood I have a still photo video and I can eliminate it – CashCow Feb 03 '15 at 09:50
  • 2
    I just tried it and even though they look identical there were small differences. 1 and 3 were closer matching as they were identical size but differed in a few places. – CashCow Feb 03 '15 at 22:33
  • 16
    `sddefault.jpg` and `maxresdefault.jpg` formats are no longer working – clami219 Mar 31 '15 at 09:27
  • 8
    @munissor that is NOT TRUE, **0.jpg IS NOT ALWAYS fullsize** version... It might be, but it is not a rule... – jave.web Apr 14 '15 at 07:42
  • 1
    On maxresdefault.jpg, if using a custom thumbnail in YouTube, we found the image must be a 16:9 aspect ratio otherwise it will default to the YouTube image. – Dean Whitehouse Jun 12 '15 at 10:41
  • to fetch the ID this question might be helpful: http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url – KNU Nov 06 '15 at 11:41
  • 12
    @jave.web @clami219 Since the `sddefault` and `maxresdefault` are not always available . Does the `mqdefault` works for all videos? What is the best URL to get thumbnail without the 2 black boders (at the top and the bottom)? – Ne AS Nov 09 '16 at 11:32
  • @Llg 2 black boders is something you can't really predict, it depends in what ratio is thumbnail vs in what ratio is video. I am not sure about which are always available, if you are too concerned about that, you should use some YouTube API. Sidenote: lately I haven't noticed video without `maxresdefault` but that is just subjective... – jave.web Nov 09 '16 at 14:02
  • 3
    While this works for most of the videos I tried last couple hours but strangely it didn't work out for this: https://img.youtube.com/vi/vJ5ZCBbAPk/0.jpg . But Youtube seems to generate the video thumnail in website just fine. Any thoughts guys? – fluffyBatman Jan 05 '17 at 10:17
  • 4
    I have noticed that depending on the age of the video and the uploaded quality, some images will not be a standard expected size. Mainly the "maxresdefault.jpg ". So for testing image size, I made this page http://www.myonlinelocation.com/YouTube_Play/VideoThumbnails/ – Tempus Feb 08 '17 at 13:10
  • 2
    It's not working when there is a ' - ' symbol in the video id (-oCXMrICJgY in https://m.youtube.com/watch?v=-oCXMrICJgY ) how to solve this issue ?? – Arun Ravindranath Feb 15 '18 at 10:17
  • 2
    I have to manually select `` every time. Can this be updated for easier use? If it was `https://img.youtube.com/vi/YOUTUBEVIDEOID/default.jpg` it would just need a double click. –  Feb 24 '18 at 18:38
  • 17
    If someone is wondering how to get sizes for not default: I just tried (and it actually works) that format names work as prefix. So you can get `maxres2.jpg`, `hq2.jpg`, `hq3.jpg`, etc. – Hernan Feb 09 '19 at 17:33
  • 1
    is this somewhere officially documented?!! – mordad Jul 26 '21 at 17:40
  • 2
    some videos do not have the thumnail. why? – Nathan B Nov 15 '21 at 09:47
  • This approach worked well for me, but the only URL format that worked was `https://i.ytimg.com/vi//hqdefault.jpg` – Dan B Feb 22 '23 at 08:49
  • It doesn't work for some videos.. Is there maybe some settings from videos owners that restrict us from getting thumbnails? – Whirlwind Aug 10 '23 at 13:35
  • This answer no longer works – Cybernetic Aug 16 '23 at 00:36
432

You can use YouTube Data API to retrieve video thumbnails, caption, description, rating, statistics and more. API version 3 requires a key*. Obtain the key and create a videos: list request:

https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=VIDEO_ID

Example PHP Code

$data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=T0Jqdjbed40");
$json = json_decode($data);
var_dump($json->items[0]->snippet->thumbnails);

Output

object(stdClass)#5 (5) {
  ["default"]=>
  object(stdClass)#6 (3) {
    ["url"]=>
    string(46) "https://i.ytimg.com/vi/T0Jqdjbed40/default.jpg"
    ["width"]=>
    int(120)
    ["height"]=>
    int(90)
  }
  ["medium"]=>
  object(stdClass)#7 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/mqdefault.jpg"
    ["width"]=>
    int(320)
    ["height"]=>
    int(180)
  }
  ["high"]=>
  object(stdClass)#8 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/hqdefault.jpg"
    ["width"]=>
    int(480)
    ["height"]=>
    int(360)
  }
  ["standard"]=>
  object(stdClass)#9 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/sddefault.jpg"
    ["width"]=>
    int(640)
    ["height"]=>
    int(480)
  }
  ["maxres"]=>
  object(stdClass)#10 (3) {
    ["url"]=>
    string(52) "https://i.ytimg.com/vi/T0Jqdjbed40/maxresdefault.jpg"
    ["width"]=>
    int(1280)
    ["height"]=>
    int(720)
  }
}

* Not only that you need a key, you might be asked for billing information depending on the number of API requests you plan to make. However, few thousand requests per day are free.

Source article.

Conor Reid
  • 578
  • 3
  • 16
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 6
    FYI: i did not change the code to fit the new JSON structure. The code in your getJSON is wrong. You used `jsonc` instead of `json` for getJSON. It's failing because of your wrong JSON structure. – mauris Jun 24 '12 at 07:41
  • 5
    Only the first example can use `jsonc`. The jQuery and PHP examples **MUST** use `json`. And I have updated the code to conform to the new JSON structure. I am using the code right now and it's working LIVE. so don't say it's not working without reading the changes. Thanks! – mauris Jun 24 '12 at 07:44
  • 7
    *The jQuery and PHP examples MUST use json*... can you provide a reference? Also, requesting a specific API version number (`v=2`) takes care of API changes. – Salman A Jun 24 '12 at 07:47
  • 4
    The gdata call does not return whether maxresdefault.jpg is available for videos where it is available, only mq/hq/sd. – Aaron May 20 '13 at 18:56
  • 2
    API v3 is VERY badly documented. They give you sample code but the "reference" section is very short of detail. Some things that should be relatively "obvious" seem to require extreme workarounds. – CashCow Feb 03 '15 at 09:51
336

What Asaph said is right. However, not every YouTube video contains all nine thumbnails. Also, the thumbnails' image sizes depends on the video (the numbers below are based on one). There are some thumbnails guaranteed to exist:

Width | Height | URL
------|--------|----
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/1.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/2.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/3.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/default.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq1.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq2.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq3.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mqdefault.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/0.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq1.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq2.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq3.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hqdefault.jpg

Additionally, the some other thumbnails may or may not exist. Their presence is probably based on whether the video is high-quality.

Width | Height | URL
------|--------|----
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd1.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd2.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd3.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sddefault.jpg
1280  | 720    | https://i.ytimg.com/vi/<VIDEO ID>/hq720.jpg
1920  | 1080   | https://i.ytimg.com/vi/<VIDEO ID>/maxresdefault.jpg

You can find JavaScript and PHP scripts to retrieve thumbnails and other YouTube information in:

You can also use the YouTube Video Information Generator tool to get all the information about a YouTube video by submitting a URL or video id.

Zombo
  • 1
  • 62
  • 391
  • 407
AGMG
  • 3,618
  • 1
  • 16
  • 14
91

In YouTube API V3 we can also use these URLs for obtaining thumbnails... They are classified based on their quality.

https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/default.jpg -   default
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg - medium 
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg - high
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/sddefault.jpg - standard

And for the maximum resolution..

https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

One advantage of these URLs over the URLs in the first answer is that these URLs don't get blocked by firewalls.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Naren
  • 2,231
  • 1
  • 25
  • 45
  • 3
    Are these images suppose to be placed in an img tag and should just work because I am trying to include the link with the right youtube video id and put them within the img tag but I keep getting a 404 – Lion789 Nov 01 '13 at 23:08
  • 5
    @Lion789 These URLs works fine when it is placed in an img tag..The problem might be a wrong video Id or the requested resolution may not be available but you won't get the 404 with these errors.Please check the url of the img tag. – Naren Nov 04 '13 at 05:42
  • 2
    Is it confirmed that the urls will keep working after API v2 will be stopped? – Daniele B Apr 14 '15 at 13:19
  • 1
    @DanieleB These URLs still work. Do you know how to check whether these URLs will work after API v2? – Naren Apr 15 '15 at 04:31
65

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.

Zombo
  • 1
  • 62
  • 391
  • 407
LuTz
  • 1,493
  • 1
  • 15
  • 25
  • 3
    This is not available for many videos. Eg: http://i.ytimg.com/vi_webp/mJ8tq8AnNis/mqdefault.webp – NickG Jul 08 '16 at 15:43
  • 4
    @NickG : It works if you remove `_webp` and change the extension to `.jpg`. Working example : http://i.ytimg.com/vi/mJ8tq8AnNis/mqdefault.jpg , I'm not sure about the aspect ratio. – LuTz Jul 09 '16 at 16:42
  • Thank you. Is there a way to get `sddefault` without black bars? https://img.youtube.com/vi_webp/dQw4w9WgXcQ/sddefault.webp keeps returning image with black bars. – Akshay K Nair Aug 23 '21 at 09:09
62

If you want the biggest image from YouTube for a specific video ID, then the URL should be something like this:

http://i3.ytimg.com/vi/SomeVideoIDHere/0.jpg

Using the API, you can pick up the default thumbnail image. Simple code should be something like this:

//Grab the default thumbnail image
$attrs = $media->group->thumbnail[1]->attributes();
$thumbnail = $attrs['url'];
$thumbnail = substr($thumbnail, 0, -5);
$thumb1 = $thumbnail."default.jpg";

// Grab the third thumbnail image
$thumb2 = $thumbnail."2.jpg";

// Grab the fourth thumbnail image.
$thumb3 = $thumbnail."3.jpg";

// Using simple cURL to save it your server.
// You can extend the cURL below if you want it as fancy, just like
// the rest of the folks here.

$ch = curl_init ("$thumb1");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata = curl_exec($ch);
curl_close($ch);

// Using fwrite to save the above
$fp = fopen("SomeLocationInReferenceToYourScript/AnyNameYouWant.jpg", 'w');

// Write the file
fwrite($fp, $rawdata);

// And then close it.
fclose($fp);
yivi
  • 42,438
  • 18
  • 116
  • 138
PoorBoy
  • 653
  • 5
  • 2
37

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;
}
Henrik Albrechtsson
  • 1,707
  • 2
  • 17
  • 17
34

YouTube is owned by Google and Google likes to have a reasonable number of images for different screen sizes, hence its images are stored in different sizes. Here is an example of how your thumbnail will be like:

Low quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg

Medium quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg

High quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg

Maximum quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
life evader
  • 970
  • 8
  • 16
33

In YouTube Data API v3, you can get video's thumbnails with the videos->list function. From snippet.thumbnails.(key), you can pick the default, medium or high resolution thumbnail, and get its width, height and URL.

You can also update thumbnails with the thumbnails->set functionality.

For examples, you can check out the YouTube API Samples project. (PHP ones.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ibrahim Ulukaya
  • 12,767
  • 1
  • 33
  • 36
33

You can get the Video Entry which contains the URL to the video's thumbnail. There's example code in the link. Or, if you want to parse XML, there's information here. The XML returned has a media:thumbnail element, which contains the thumbnail's URL.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
28
// Get image form video URL
$url = $video['video_url'];

$urls = parse_url($url);

//Expect the URL to be http://youtu.be/abcd, where abcd is the video ID
if ($urls['host'] == 'youtu.be') :

    $imgPath = ltrim($urls['path'],'/');

//Expect the URL to be http://www.youtube.com/embed/abcd
elseif (strpos($urls['path'],'embed') == 1) :

    $imgPath = end(explode('/',$urls['path']));

//Expect the URL to be abcd only
elseif (strpos($url,'/') === false):

    $imgPath = $url;

//Expect the URL to be http://www.youtube.com/watch?v=abcd
else :

    parse_str($urls['query']);

    $imgPath = $v;

endif;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mahendra Tyagi
  • 417
  • 4
  • 3
22

YouTube is serving thumbnails from 2 servers. You just need to replace <YouTube_Video_ID_HERE> with your own YouTube video id. These days webP is best format for fast loading of images due to small image size.

https://img.youtube.com https://i.ytimg.com

Examples are with https://i.ytimg.com server just because it’s shorter, no other particular reason. You can use both.

Player Background Thumbnail (480x360):

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/0.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/0.jpg

Video frames thumbnails (120x90)

WebP:
Start: https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/1.webp
Middle: https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/2.webp
End: https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/3.webp

JPG:
Start: https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/1.jpg
Middle: https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/2.jpg
End: https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/3.jpg

Lowest quality thumbnail (120x90)

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/default.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/default.jpg

Medium quality thumbnail (320x180)

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/mqdefault.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg

High quality thumbnail (480x360)

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/hqdefault.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg

Standard quality thumbnail (640x480)

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/sddefault.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg

Unscaled thumbnail resolution

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/maxresdefault.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg
Mark Fulghum
  • 550
  • 4
  • 13
18

YouTube API version 3 up and running in 2 minutes

If all you want to do is search YouTube and get associated properties:

  1. Get a public API -- This link gives a good direction

  2. 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

Community
  • 1
  • 1
Chris
  • 18,075
  • 15
  • 59
  • 77
18

Another good alternative would be to use the oEmbed API which is supported by YouTube.

You simply add your YouTube URL to the oEmbed URL and you'll receive a JSON including a thumbnail and the HTML code for embedding.

Example:

http://www.youtube.com/oembed?format=json&url=http%3A//youtube.com/watch%3Fv%3DxUeJdWYdMmQ

Would give you:

{
  "height":270,
  "width":480,
  "title":"example video for 2020",
  "thumbnail_width":480,
  "html":"...",
  "thumbnail_height":360,
  "version":"1.0",
  "provider_name":"YouTube",
  "author_url":"https:\/\/www.youtube.com\/channel\/UCza6VSQUzCON- AzlsrOLwaA",
  "thumbnail_url":"https:\/\/i.ytimg.com\/vi\/xUeJdWYdMmQ\/hqdefault.jpg",
  "author_name":"Pokics",
  "provider_url":"https:\/\/www.youtube.com\/",
  "type":"video"
}

Read the documentation for more information.

Andresch Serj
  • 35,217
  • 15
  • 59
  • 101
15

Use:

https://www.googleapis.com/youtube/v3/videoCategories?part=snippet,id&maxResults=100&regionCode=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.

Community
  • 1
  • 1
Nikh1414
  • 1,238
  • 2
  • 19
  • 35
15

I have used YouTube thumbnails in this way:

$url = 'http://img.youtube.com/vi/' . $youtubeId . '/0.jpg';
$img = dirname(__FILE__) . '/youtubeThumbnail_'  . $youtubeId . '.jpg';
file_put_contents($img, file_get_contents($url));

Remember YouTube prevents to include images directly from their server.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
15

You can get the video ID from the YouTube video url using parse_url ,parse_str and then insert in to the predictive urls for images. Thanks to YouTube for the predictive URLs

$videoUrl = "https://www.youtube.com/watch?v=8zy7wGbQgfw";
parse_str( parse_url( $videoUrl, PHP_URL_QUERY ), $my_array_of_vars );
$ytID = $my_array_of_vars['v']; //gets video ID

print "https://img.youtube.com/vi/$ytID/maxresdefault.jpg";
print "https://img.youtube.com/vi/$ytID/mqdefault.jpg";
print "https://img.youtube.com/vi/$ytID/hqdefault.jpg";
print "https://img.youtube.com/vi/$ytID/sddefault.jpg";
print "https://img.youtube.com/vi/$ytID/default.jpg";

You can use this tool to generate YouTube thumbnails

https://youtube-thumbnail-tool.com

Duke
  • 35,420
  • 13
  • 53
  • 70
13

Just to add/expand on the solutions given, I feel it is necessary to note that, as I had this problem myself, one can actually grab multiple YouTube videos content, in this case, thumbnails, with one HTTP request:

Using a Rest Client, in this case, HTTPFUL, you can do something like this:

<?php
header("Content-type", "application/json");

//download the httpfull.phar file from http://phphttpclient.com
include("httpful.phar");

$youtubeVidIds= array("nL-rk4bgJWU", "__kupr7KQos", "UCSynl4WbLQ", "joPjqEGJGqU", "PBwEBjX3D3Q");


$response = \Httpful\Request::get("https://www.googleapis.com/youtube/v3/videos?key=YourAPIKey4&part=snippet&id=".implode (",",$youtubeVidIds)."")

->send();

print ($response);

?>
Hlawuleka MAS
  • 550
  • 5
  • 11
13

YouTube Data API

YouTube provides us the four generated images for every video through the Data API (v3), for example,

  1. https://i.ytimg.com/vi/V_zwalcR8DU/maxresdefault.jpg

  2. https://i.ytimg.com/vi/V_zwalcR8DU/sddefault.jpg

  3. https://i.ytimg.com/vi/V_zwalcR8DU/hqdefault.jpg

  4. https://i.ytimg.com/vi/V_zwalcR8DU/mqdefault.jpg

Getting access to the images via the API

  1. First get your public API key at Google API Console.
  2. As per YouTube's thumbnail reference in the API documentation, you need to access the resources on snippet.thumbnails.
  3. As per this, you need to phrase your URL like this -

    www.googleapis.com/youtube/v3/videos?part=snippet&id=`yourVideoId`&key=`yourApiKey`
    

Now change your video ID and your API key to the your respective video-id and api-key and its response will be a JSON output providing you the four links in the thumbnails of snippet variable (if all are available).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daksh M.
  • 4,589
  • 4
  • 30
  • 46
12

A simple PHP function I created for the YouTube thumbnail and the types are

  • default
  • hqdefault
  • mqdefault
  • sddefault
  • maxresdefault

 

function get_youtube_thumb($link,$type){

    $video_id = explode("?v=", $link);

    if (empty($video_id[1])){
        $video_id = explode("/v/", $link);
        $video_id = explode("&", $video_id[1]);
        $video_id = $video_id[0];
    }
    $thumb_link = "";

    if($type == 'default'   || $type == 'hqdefault' ||
       $type == 'mqdefault' || $type == 'sddefault' ||
       $type == 'maxresdefault'){

        $thumb_link = 'http://img.youtube.com/vi/'.$video_id.'/'.$type.'.jpg';

    }elseif($type == "id"){
        $thumb_link = $video_id;
    }
    return $thumb_link;}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arun Yokesh
  • 1,346
  • 17
  • 19
12
https://i.ytimg.com/vi/<--Video ID-->/default.jpg

Image Size Weight 120px Height 90px

https://i.ytimg.com/vi/<--Video ID-->/mqdefault.jpg

Image Size Weight 320px Height 180px

https://i.ytimg.com/vi/<--Video ID-->/hqdefault.jpg

Image Size Weight 480px Height 360px

https://i.ytimg.com/vi/<--Video ID-->/sddefault.jpg

Image Size Weight 640px Height 480px

https://i.ytimg.com/vi/<--Video ID-->/maxresdefault.jpg

Image Size Weight 1280px Height 720px

CodAIK
  • 715
  • 7
  • 7
10

If you're using the public API, the best way to do it is using if statements.

If the video is public or unlisted, you set the thumbnail using the URL method. If the video is private you use the API to get the thumbnail.

<?php
    if($video_status == 'unlisted'){
        $video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
        $video_status = '<i class="fa fa-lock"></i>&nbsp;Unlisted';
    }
    elseif($video_status == 'public'){
        $video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
        $video_status = '<i class="fa fa-eye"></i>&nbsp;Public';
    }
    elseif($video_status == 'private'){
        $video_thumbnail = $playlistItem['snippet']['thumbnails']['maxres']['url'];
        $video_status = '<i class="fa fa-lock"></i>&nbsp;Private';
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Harvey Connor
  • 146
  • 4
  • 19
9

I think there is a lot of answers for thumbnail, but I want to add some other URLs to get YouTube thumbnail very easily. I am just taking some text from Asaph's answer. Here are some URLs to get YouTube thumbnails:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/default.jpg

For the high quality version of the thumbnail use a URL similar to this:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a URL similar to the high quality:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

For the standard definition version of the thumbnail, use a URL similar to this:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

For the maximum resolution version of the thumbnail use a URL similar to this:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
Kumar
  • 1,187
  • 18
  • 31
9

Although there are already many answers, but for new visitors I will leave mine with two options for obtaining a thumbnail.

Getting Thumbnail via YouTube Data API

  1. Register your app with Google Cloud Platform and activate YouTube Data API v3 library
  2. Create an API Key in the Credentials section. This way you will get a key to access the API
  3. And send a request for information about the video, including getting a thumbnail.

$api_key = 'YOUR_API_KEY';
$youtube_video_id = 'jNQXAC9IVRw';
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://www.googleapis.com/youtube/v3/videos?key='.$api_key.'&part=snippet&id='.$youtube_video_id,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
)); 

$response = curl_exec($curl); 
curl_close($curl);

$response = json_decode($response,true); 

print_r($response); // result with video information and thumbnails

Getting a thumbnail from a direct link without an API

In addition to the API, thumbnails can be obtained via a direct link, like this:

https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg

Let's consider this option in detail:

 https://i.ytimg.com/vi/<YOUTUBE_VIDEO_ID>/<SIZE_VALUE>.jpg 

Where:

  • YOUTUBE_VIDEO_ID : Your video ID
  • SIZE_VALUE : Thumbnail size. The variable can contain such values: default, mqdefault, hqdefault, sddefault, maxresdefault

$youtube_video_id = 'jNQXAC9IVRw';
$size = 'hqdefault';

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://i.ytimg.com/vi/{$youtube_video_id}/{$size}.jpg",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);

// Write the file
$handle = fopen("image/filename.jpg", 'w'); // set your directory and filename
fwrite($handle, $response);
fclose($handle);
emrdev
  • 2,155
  • 3
  • 9
  • 15
8

Method 1:

You can find all information for a YouTube video with a JSON page which has even "thumbnail_url", http://www.youtube.com/oembed?format=json&url={your video URL goes here}

Like final URL look + PHP test code

$data = file_get_contents("https://www.youtube.com/oembed?format=json&url=https://www.youtube.com/watch?v=_7s-6V_0nwA");
$json = json_decode($data);
var_dump($json);

Output

object(stdClass)[1]
  public 'width' => int 480
  public 'version' => string '1.0' (length=3)
  public 'thumbnail_width' => int 480
  public 'title' => string 'how to reminder in window as display message' (length=44)
  public 'provider_url' => string 'https://www.youtube.com/' (length=24)
  public 'thumbnail_url' => string 'https://i.ytimg.com/vi/_7s-6V_0nwA/hqdefault.jpg' (length=48)
  public 'author_name' => string 'H2 ZONE' (length=7)
  public 'type' => string 'video' (length=5)
  public 'author_url' => string 'https://www.youtube.com/channel/UC9M35YwDs8_PCWXd3qkiNzg' (length=56)
  public 'provider_name' => string 'YouTube' (length=7)
  public 'height' => int 270
  public 'html' => string '<iframe width="480" height="270" src="https://www.youtube.com/embed/_7s-6V_0nwA?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>' (length=171)
  public 'thumbnail_height' => int 360

For details, you can also see How to get a YouTube video thumbnail using id or https://www.youtube.com/watch?v=mXde7q59BI8 video tutorial 1

Method 2:

Using YouTube image link, https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg

Method 3:

Using browser source code for getting thumbnail using video URL link -go to video source code and search for thumbnailurl. Now you can use this URL into your source code:

{img src="https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg"}

For details you can also see How to get a YouTube video thumbnail using id or https://www.youtube.com/watch?v=9f6E8MeM6PI video tutorial 2

Hassan Saeed
  • 6,326
  • 1
  • 39
  • 37
6
    function get_video_thumbnail( $src ) {
            $url_pieces = explode('/', $src);
            if( $url_pieces[2] == 'dai.ly'){
                $id = $url_pieces[3];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if($url_pieces[2] == 'www.dailymotion.com'){
                $id = $url_pieces[4];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if ( $url_pieces[2] == 'vimeo.com' ) { // If Vimeo
                $id = $url_pieces[3];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'youtu.be' ) { // If Youtube
                $extract_id = explode('?', $url_pieces[3]);
                $id = $extract_id[0];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            }else if ( $url_pieces[2] == 'player.vimeo.com' ) { // If Vimeo
                $id = $url_pieces[4];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'www.youtube.com' ) { // If Youtube
                $extract_id = explode('=', $url_pieces[3]);
                $id = $extract_id[1];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            } else{
                $thumbnail = tim_thumb_default_image('video-icon.png', null, 147, 252);
            }
            return $thumbnail;
        }

get_video_thumbnail('https://vimeo.com/154618727');
get_video_thumbnail('https://www.youtube.com/watch?v=SwU0I7_5Cmc');
get_video_thumbnail('https://youtu.be/pbzIfnekjtM');
get_video_thumbnail('http://www.dailymotion.com/video/x5thjyz');
Nimesh Vagadiya
  • 602
  • 3
  • 8
  • 18
6

Here's the top answer optimized for manual use. The video ID token without separators enables selecting with a double click.

Each YouTube video has four generated images. They are predictably formatted as follows:

https://img.youtube.com/vi/YOUTUBEVIDEOID/0.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/1.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/2.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/3.jpg

The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (ie. one of 1.jpg, 2.jpg, 3.jpg) is:

https://img.youtube.com/vi/YOUTUBEVIDEOID/default.jpg

For the high quality version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a URL similar to the HQ:

https://img.youtube.com/vi/YOUTUBEVIDEOID/mqdefault.jpg

For the standard definition version of the thumbnail, use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/sddefault.jpg

For the maximum resolution version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/maxresdefault.jpg

All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example URLs above.

Alternatively, you can use the YouTube Data API (v3) to get thumbnail images.

5

Save this code in empty.php file and test it.

<img src="<?php echo youtube_img_src('9bZkp7q19f0', 'high');?>" />
<?php
// Get a YOUTUBE video thumb image's source url for IMG tag "src" attribute:
// $ID = YouYube video ID (string)
// $size = string (default, medium, high or standard)
function youtube_img_src ($ID = null, $size = 'default') {
    switch ($size) {
        case 'medium':
            $size = 'mqdefault';
            break;
        case 'high':
            $size = 'hqdefault';
            break;
        case 'standard':
            $size = 'sddefault';
            break;
        default:
            $size = 'default';
            break;
    }
    if ($ID) {
        return sprintf('https://img.youtube.com/vi/%s/%s.jpg', $ID, $size);
    }
    return 'https://img.youtube.com/vi/ERROR/1.jpg';
}

There are some thumbnails guaranteed to exist:

Width | Height | URL
------|--------|----
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/1.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/2.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/3.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/default.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq1.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq2.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq3.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mqdefault.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/0.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq1.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq2.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq3.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hqdefault.jpg

Thanks.

Ali Han
  • 509
  • 7
  • 10
4

This is my client-side-only no-API-key-required solution.

YouTube.parse('https://www.youtube.com/watch?v=P3DGwyl0mJQ').then(_ => console.log(_))

The code:

import { parseURL, parseQueryString } from './url'
import { getImageSize } from './image'

const PICTURE_SIZE_NAMES = [
    // 1280 x 720.
    // HD aspect ratio.
    'maxresdefault',
    // 629 x 472.
    // non-HD aspect ratio.
    'sddefault',
    // For really old videos not having `maxresdefault`/`sddefault`.
    'hqdefault'
]

// - Supported YouTube URL formats:
//   - http://www.youtube.com/watch?v=My2FRPA3Gf8
//   - http://youtu.be/My2FRPA3Gf8
export default
{
    parse: async function(url)
    {
        // Get video ID.
        let id
        const location = parseURL(url)
        if (location.hostname === 'www.youtube.com') {
            if (location.search) {
                const query = parseQueryString(location.search.slice('/'.length))
                id = query.v
            }
        } else if (location.hostname === 'youtu.be') {
            id = location.pathname.slice('/'.length)
        }

        if (id) {
            return {
                source: {
                    provider: 'YouTube',
                    id
                },
                picture: await this.getPicture(id)
            }
        }
    },

    getPicture: async (id) => {
        for (const sizeName of PICTURE_SIZE_NAMES) {
            try {
                const url = getPictureSizeURL(id, sizeName)
                return {
                    type: 'image/jpeg',
                    sizes: [{
                        url,
                        ...(await getImageSize(url))
                    }]
                }
            } catch (error) {
                console.error(error)
            }
        }
        throw new Error(`No picture found for YouTube video ${id}`)
    },

    getEmbeddedVideoURL(id, options = {}) {
        return `https://www.youtube.com/embed/${id}`
    }
}

const getPictureSizeURL = (id, sizeName) => `https://img.youtube.com/vi/${id}/${sizeName}.jpg`

Utility image.js:

// Gets image size.
// Returns a `Promise`.
function getImageSize(url)
{
    return new Promise((resolve, reject) =>
    {
        const image = new Image()
        image.onload = () => resolve({ width: image.width, height: image.height })
        image.onerror = reject
        image.src = url
    })
}

Utility url.js:

// Only on client side.
export function parseURL(url)
{
    const link = document.createElement('a')
    link.href = url
    return link
}

export function parseQueryString(queryString)
{
    return queryString.split('&').reduce((query, part) =>
    {
        const [key, value] = part.split('=')
        query[decodeURIComponent(key)] = decodeURIComponent(value)
        return query
    },
    {})
}
catamphetamine
  • 4,489
  • 30
  • 25
3

Here is a simple function I created for getting the thumbnails. It is easy to understand and use.

$link is the YouTube link copied exactly as it is in the browser, for example, https://www.youtube.com/watch?v=BQ0mxQXmLsk

function get_youtube_thumb($link){
    $new = str_replace('https://www.youtube.com/watch?v=', '', $link);
    $thumbnail = 'https://img.youtube.com/vi/' . $new . '/0.jpg';
    return $thumbnail;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sodruldeen Mustapha
  • 1,135
  • 10
  • 22
  • This only works when the url has no other query parameters. – Ma Kobi May 03 '18 at 09:52
  • yes, all youtube videos follows the format while watching, you can copy the link from the browser – Sodruldeen Mustapha May 04 '18 at 11:01
  • What if you have another parameter like `&t=227s`? – Ma Kobi May 04 '18 at 11:04
  • 1
    i understand your point, but the standard youtube videos come without other parameters but when the need arise, you can filter the link before the first line of the function. Do you need help in filtering the link to make sure it ignores every other thing except the needed? – Sodruldeen Mustapha May 04 '18 at 12:23
3

Use img.youtube.com/vi/YouTubeID/ImageFormat.jpg

Here image formats are different like default, hqdefault, maxresdefault.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
shpwebhost
  • 66
  • 11