How do I get a YouTube video thumbnail from the YouTube API?

Ryan Source

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?

phpcurlyoutubeyoutube-apiyoutube-data-api

Answers

answered 9 years ago Asaph #1

Each YouTube video has 4 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 (ie. 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.

answered 9 years ago keyboardP #2

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.

answered 9 years ago Salman A #3

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 million requests per day are free.

Source article.

answered 8 years ago PoorBoy #4

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 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);

answered 5 years ago Ibrahim Ulukaya #5

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

answered 5 years ago Mahendra Tyagi #6

// 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;

answered 5 years ago Naren #7

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.

answered 5 years ago AGMG #8

What Asaph said is right. However, not every YouTube video contains all nine thumbnails, but there are seven thumbnails for every video. They are:

(Image size depends on video.)

  • Player Background Thumbnail (480x360 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/0.jpg

  • Start Thumbnail (120x90 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/1.jpg

  • Middle Thumbnail (120x90 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/2.jpg

  • End Thumbnail (120x90 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/3.jpg

  • High Quality Thumbnail (480x360 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/hqdefault.jpg

  • Medium Quality Thumbnail (320x180 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/mqdefault.jpg

  • Normal Quality Thumbnail (120x90 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/default.jpg

And additionally, the next two thumbnails may or may not exist. For HQ videos they exist.

  • Standard Definition Thumbnail (640x480 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/sddefault.jpg

  • Maximum Resolution Thumbnail (1920x1080 pixels)
    https://i1.ytimg.com/vi/G0wGs3useV8/maxresdefault.jpg

You can get the JavaScript and PHP scripts to retrieve thumbnails and other YouTube information in

Also use the tool YouTube Video Information Generator to get all the information of a YouTube video by submitting a URL or video ID.

answered 5 years ago Henrik Albrechtsson #9

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;
}

answered 5 years ago Scott Joudry #10

I found this nifty tool that allows you to create the image with the YouTube play button placed over the image:

answered 5 years ago Chris #11

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

answered 5 years ago Nikh1414 #12

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.

answered 3 years ago blacksunshineCoding #13

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

answered 3 years ago LuTz #14

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

answered 3 years ago Arun Yokesh #15

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;}
    

answered 3 years ago life evader #16

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 like will he 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

answered 2 years ago Hlawuleka MAS #17

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);

?>

answered 2 years ago Harvey Connor #18

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';
}

answered 2 years ago Kumar #19

I think their are a lots of answer 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 url 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 HQ:

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

Hope it helps someone in near future.

answered 2 years ago Rajat Jain #20

public const string tubeThumb = "http://i.ytimg.com/vi/[id]/hqdefault.jpg";
vid.Thumbnail = tubeThumb.Replace("[id]", vid.VideoID);

answered 2 years ago Andresch Serj #21

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%3DDLzxrzFCyOs

Would give you:

{
  thumbnail_url: "https://i.ytimg.com/vi/DLzxrzFCyOs/hqdefault.jpg",
  width: 459,
  author_name: "AllKindsOfStuff",
  version: "1.0",
  author_url: "https://www.youtube.com/channel/UCLNd5EtH77IyN1frExzwPRQ",
  thumbnail_width: 480,
  type: "video",
  provider_url: "https://www.youtube.com/",
  html: "<iframe width="459" height="344" src="https://www.youtube.com/embed/DLzxrzFCyOs?feature=oembed" frameborder="0" allowfullscreen></iframe>",
  title: "Some title bla bla foo bar",
  thumbnail_height: 360,
  provider_name: "YouTube",
  height: 344
}

Read the Documentation for more Information.

answered 2 years ago Daksh Miglani #22

YouTube Data API

YouTube Provides us the 4 generated images for every video through the Data API (v3), For Ex -

  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 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 yourVideoId and yourApiKey to the your respective video-id and api-key and its response will be a JSON output providing you the 4links in the thumbnails of snippet variable (If all are available).

answered 1 year ago Shahzaib Chadhar #23

Save file as .js

  var maxVideos = 5;
  $(document).ready(function(){
  $.get(
    "https://www.googleapis.com/youtube/v3/videos",{
      part: 'snippet,contentDetails',
      id:'your_video_id',
      kind: 'youtube#videoListResponse',
      maxResults: maxVideos,
      regionCode: 'IN',
      key: 'Your_API_KEY'},
      function(data){
        var output;
        $.each(data.items, function(i, item){
          console.log(item);
                thumb = item.snippet.thumbnails.high.url;
          output = '<div id="img"><img src="' + thumb + '"></div>';
          $('#thumbnail').append(output);
        })
        
      }
    );
}); 
.main{
 width:1000px;
 margin:auto;
}
#img{
float:left;
display:inline-block;
margin:5px;
}
<!DOCTYPE html>
<html>
<head>
  <title>Thumbnails</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="main">
 <ul id="thumbnail"> </ul>
</div>
</body>
</html>

answered 12 months ago Nimesh Vagadiya #24

    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');

answered 8 months ago Lycan #25

Top answer optimized for manual use. Video ID token without separators enables selecting with a double click.

Each YouTube video has 4 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.

answered 7 months ago Ways Test #26

package com.app.download_video_demo;

import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;


// get Picasso jar file and put that jar file in libs folder

public class Youtube_Video_thumnail extends Activity
{
    ImageView iv_youtube_thumnail,iv_play;
    String videoId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.youtube_video_activity);

        init();

        try 
        {
            videoId=extractYoutubeId("http://www.youtube.com/watch?v=t7UxjpUaL3Y");

            Log.e("VideoId is->","" + videoId);

            String img_url="http://img.youtube.com/vi/"+videoId+"/0.jpg"; // this is link which will give u thumnail image of that video

            // picasso jar file download image for u and set image in imagview

            Picasso.with(Youtube_Video_thumnail.this)
            .load(img_url) 
            .placeholder(R.drawable.ic_launcher) 
            .into(iv_youtube_thumnail);

        } 
        catch (MalformedURLException e) 
        {
            e.printStackTrace();
        }

    }
    public void init()
    {
        iv_youtube_thumnail=(ImageView)findViewById(R.id.img_thumnail);
        iv_play=(ImageView)findViewById(R.id.iv_play_pause);
    }

    // extract youtube video id and return that id
    // ex--> "http://www.youtube.com/watch?v=t7UxjpUaL3Y"
    // videoid is-->t7UxjpUaL3Y


    public String extractYoutubeId(String url) throws MalformedURLException {
        String query = new URL(url).getQuery();
        String[] param = query.split("&");
        String id = null;
        for (String row : param) {
            String[] param1 = row.split("=");
            if (param1[0].equals("v")) {
                id = param1[1];
            }
        }
        return id;
    }

}

answered 6 months ago Hassan Saeed #27

Method 1:

you can find youtube video all information with 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 detail you can also see https://www.youtube.com/watch?v=mXde7q59BI8 video tutorial 1

Method 2: using youtube img 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 sorce Code: {img src="https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg"}

for detail you can also see http://hzonesp.com/php/get-youtube-video-thumbnail-using-id/ or https://www.youtube.com/watch?v=9f6E8MeM6PI video tutorial 2

answered 6 months ago Mustapha Sodruldeen #28

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 on 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;
}

answered 6 months ago Rinto George #29

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/<?php print $ytID?>/maxresdefault.jpg";
print "https://img.youtube.com/vi/<?php print $ytID?>/mqdefault.jpg";
print "https://img.youtube.com/vi/<?php print $ytID?>/hqdefault.jpg";
print "https://img.youtube.com/vi/<?php print $ytID?>/sddefault.jpg";
print "https://img.youtube.com/vi/<?php print $ytID?>/default.jpg";

You can use this tool to generate YouTube thumbnails

https://codeatools.com/get-youtube-video-thumbnails

answered 2 months ago shpwebhost #30

Use this - img.youtube.com/vi/YouTubeID/ImageFormat.jpg here image formats are different like default, hqdefault, maxresdefault.

answered 4 weeks ago asdfasdfads #31

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
    },
    {})
}

comments powered by Disqus