20

How can I access thumbnail collection of a YouTube video using the link of the video from the YouTube API. I want thumbnails to be displayed on website using PHP using the video id stored in a variable for example $link

6 Answers6

64

YouTube stores many different types of thumbnails on its server for different devices. You can access it by using the video id which every YouTube video has. You can display the images on your website using a variable $link which holds the id of the video and substituting it in the place for video_ID in the link.

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

Example:

If you want to access the thumbnail of the following video:

https://www.youtube.com/watch?v=Q-GYwhqDo6o

Video ID : Q-GYwhqDo6o

So, this is how video thumbnail link looks like:

http://img.youtube.com/vi/Q-GYwhqDo6o/mqdefault.jpg

Hope it helps. Enjoy coding.

Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78
Ronald P Mathews
  • 2,178
  • 1
  • 22
  • 26
16

To get high-quality image you can use the following URL which is fetched from youtube API

$video_id = explode("?v=", $link);
$video_id = $video_id[1];
$thumbnail="http://img.youtube.com/vi/".$video_id."/maxresdefault.jpg";
Rishi
  • 473
  • 4
  • 13
8

You can use the below code. It is work for me. Choose the image quality as per your requirement.

<?php
$youtubeID = getYouTubeVideoId('youtube video url');
$thumbURL = 'https://img.youtube.com/vi/' . $youtubeID . '/mqdefault.jpg';
print_r($thumbURL);

function getYouTubeVideoId($pageVideUrl) {
    $link = $pageVideUrl;
    $video_id = explode("?v=", $link);
    if (!isset($video_id[1])) {
        $video_id = explode("youtu.be/", $link);
    }
    $youtubeID = $video_id[1];
    if (empty($video_id[1])) $video_id = explode("/v/", $link);
    $video_id = explode("&", $video_id[1]);
    $youtubeVideoID = $video_id[0];
    if ($youtubeVideoID) {
        return $youtubeVideoID;
    } else {
        return false;
    }
}
?>
Kamal Sanghavi
  • 175
  • 1
  • 12
2

here is my handy function to download the Youtube thumbnail image

function downloadYouTubeThubnailImage($youTubeLink='',$thumbNamilQuality='',$fileNameWithExt='',$fileDownLoadPath='')
    {
        $videoIdExploded = explode('?v=', $youTubeLink);   

        if ( sizeof($videoIdExploded) == 1) 
        {
            $videoIdExploded = explode('&v=', $youTubeLink);

            $videoIdEnd = end($videoIdExploded);

            $removeOtherInVideoIdExploded = explode('&',$videoIdEnd);

            $youTubeVideoId = current($removeOtherInVideoIdExploded);
        }else{
            $videoIdExploded = explode('?v=', $youTubeLink);

            $videoIdEnd = end($videoIdExploded);

            $removeOtherInVideoIdExploded = explode('&',$videoIdEnd);

            $youTubeVideoId = current($removeOtherInVideoIdExploded);
        }

        switch ($thumbNamilQuality) 
        {
            case 'LOW':
                    $imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/sddefault.jpg';
                break;

            case 'MEDIUM':
                    $imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/mqdefault.jpg';
                break;

            case 'HIGH':
                    $imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/hqdefault.jpg';
                break;

            case 'MAXIMUM':
                    $imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/maxresdefault.jpg';
                break;
            default:
                return  'Choose The Quality Between [ LOW (or) MEDIUM  (or) HIGH  (or)  MAXIMUM]';
                break;
        }  

        if( empty($fileNameWithExt) || is_null($fileNameWithExt)  || $fileNameWithExt === '') 
        {
            $toArray = explode('/',$imageUrl);
            $fileNameWithExt = md5( time().mt_rand( 1,10 ) ).'.'.substr(strrchr(end($toArray),'.'),1);
          }

          if (! is_dir($fileDownLoadPath)) 
            {
                mkdir($fileDownLoadPath,0777,true);
            }

            file_put_contents($fileDownLoadPath.$fileNameWithExt, file_get_contents($imageUrl));
            return $fileNameWithExt;   
    }

Function Description

Argumemts

$youTubeLink Youtube url for example https://www.youtube.com/watch?v=a3ICNMQW7Ok

$thumbNamilQuality It has Many Quality Such as LOW ,MEDIUM, HIGH, MAXIMUM

Thumbnail Quality list Taken from https://stackoverflow.com/a/32346348/8487424

&& https://stackoverflow.com/a/47546113/8487424

$fileNameWithExt File Name with Extension**for example** myfavouriteimage.png

NOTE $fileNameWithExt is not mandatory it will generate the uuid based file name for Example 91b2a30d0682058ebda8d71606f5e327.jpg

if you want to put the file to the custom directory use this argument

NOTE $fileDownLoadPath is not mandatory it will generate the image file where the script is executing

Some of the sample examples

$folderpath = 'c:'.DIRECTORY_SEPARATOR.'xampp'.DIRECTORY_SEPARATOR.'htdocs'.DIRECTORY_SEPARATOR.'youtube'.DIRECTORY_SEPARATOR;

$imageName = 'mybeautfulpic.jpg';

downloadYouTubeThubnailImage('https://www.youtube.com/watch?v=a3ICNMQW7Ok','MAXIMUM',null,$folderpath );

downloadYouTubeThubnailImage('https://www.youtube.com/watch?v=a3ICNMQW7Ok','LOW',$imageName ,null);

Hope it is answered already but this function has some exta features

ManojKiran A
  • 5,896
  • 4
  • 30
  • 43
1

Google changed API on v.3 and those code from Python work exactly! You can use for PHP.

def get_small_image_url(self):
    return 'http://img.youtube.com/vi/%s/%s.jpg' % (self.video_id, random.randint(1, 3))

def get_hqdefault(self):
    return 'http://i1.ytimg.com/vi/%s/hqdefault.jpg' % self.video_id

def get_mqdefault(self):
    return 'http://i1.ytimg.com/vi/%s/mqdefault.jpg' % self.video_id

def get_sddefault(self):
    return 'http://i1.ytimg.com/vi/%s/sddefault.jpg' % self.video_id

def get_video_id(self, url):
    link = urlparse.urlparse(url)
    if link.hostname == 'youtu.be':
        return link.path[1:]
    if link.hostname in ('www.youtube.com', 'youtube.com'):
        if link.path == '/watch':
            state = urlparse.parse_qs(link.query)
            return state['v'][0]
        if link.path[:7] == '/embed/':
            return link.path.split('/')[2]
        if link.path[:3] == '/v/':
            return link.path.split('/')[2]
    return False

def get_meta(self, video_id):
    api_token = **'here your API_Token'**
    url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&id=%s&key=%s' % (video_id, api_token)
    response = json.load(urllib.urlopen(url))
    print response
    context = {
        'title': response['items'][0]['snippet']['localized']['title'],
        'desc': response['items'][0]['snippet']['localized']['description']
    }
    return context

def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
    video_id = self.get_video_id(self.url)
    meta = self.get_meta(video_id)
    self.video_id = video_id
    self.title = meta['title']
    self.description = meta['desc']
    super(Videos, self).save(
        force_insert=force_insert,
        force_update=force_update,
        using=using,
        update_fields=update_fields
    )
kdelinx
  • 29
  • 3
0

the simplest and easiest way to get youtube-video-id from a youtube link using str_replace.

$youtube_ids = str_replace("https://www.youtube.com/watch?v=", "", "https://www.youtube.com/watch?v=QBKdaUv5YaI");
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/maxresdefault.jpg';

Low-quality thumbnail:

echo 'http://img.youtube.com/vi/'.$youtube_ids.'/sddefault.jpg';

Medium quality thumbnail:

echo 'http://img.youtube.com/vi/'.$youtube_ids.'/mqdefault.jpg';

High quality thumbnail:

echo 'http://img.youtube.com/vi/'.$youtube_ids.'/hqdefault.jpg';

Maximum quality thumbnail:

echo 'http://img.youtube.com/vi/'.$youtube_ids.'/maxresdefault.jpg';
Darkcoder
  • 802
  • 1
  • 9
  • 17