首页 文章

如何从YouTube API获取YouTube视频缩略图?

提问于
浏览
2094

如果我有YouTube视频网址,有没有办法使用PHP和cURL从YouTube API获取相关缩略图?

30 回答

  • 16

    您可以获取Video Entry,其中包含链接中视频_160048的示例代码的URL . 或者,如果要解析XML,则会显示here的信息 . 返回的XML具有 media:thumbnail 元素,其中包含缩略图的URL .

  • 12

    您可以使用parse_urlparse_str从YouTube视频网址获取视频ID,然后插入图片的预测网址 . 感谢YouTube提供的预测网址

    $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";
    

    您可以使用此工具生成YouTube缩略图

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

  • 13

    亚萨说的是对的 . 但是,并非每个YouTube视频都包含所有九个缩略图 . 此外,缩略图的图像大小取决于视频(下面的数字基于一个) .

    确保存在七个缩略图:

    | Thumbnail Name      | Size (px) | URL                                              |
    |---------------------|-----------|--------------------------------------------------|
    | Player Background   | 480x360   | https://i1.ytimg.com/vi/<VIDEO ID>/0.jpg         |
    | Start               | 120x90    | https://i1.ytimg.com/vi/<VIDEO ID>/1.jpg         |
    | Middle              | 120x90    | https://i1.ytimg.com/vi/<VIDEO ID>/2.jpg         |
    | End                 | 120x90    | https://i1.ytimg.com/vi/<VIDEO ID>/3.jpg         |
    | High Quality        | 480x360   | https://i1.ytimg.com/vi/<VIDEO ID>/hqdefault.jpg |
    | Medium Quality      | 320x180   | https://i1.ytimg.com/vi/<VIDEO ID>/mqdefault.jpg |
    | Normal Quality      | 120x90    | https://i1.ytimg.com/vi/<VIDEO ID>/default.jpg   |
    

    此外,其他两个缩略图可能存在也可能不存在 . 他们的存在可能取决于视频是否是高质量的 .

    | Thumbnail Name      | Size (px) | URL                                                  |
    |---------------------|-----------|------------------------------------------------------|
    | Standard Definition | 640x480   | https://i1.ytimg.com/vi/<VIDEO ID>/sddefault.jpg     |
    | Maximum Resolution  | 1920x1080 | https://i1.ytimg.com/vi/<VIDEO ID>/maxresdefault.jpg |
    

    您可以在以下位置找到JavaScript和PHP脚本来检索缩略图和其他YouTube信息:

    您还可以使用YouTube Video Information Generator工具通过提交网址或视频ID来获取有关YouTube视频的所有信息 .

  • 4

    YouTube Data API

    YouTube通过Data API(v3)为我们提供每个视频的4个生成图像,对于Ex -

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

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

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

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

    通过API访问图像

    • 首先在Google API Console获取您的公共API密钥 .

    • 根据API Documentation中的YouTube缩略图参考,您需要访问snippet.thumbnails上的资源 .

    • 如此,你需要像这样短语你的网址 -

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

    现在将yourVideoId和yourApiKey更改为您的相应视频ID和api-key,其响应将是一个JSON输出,为您提供片段变量缩略图中的4个链接(如果全部可用) .

  • 362

    我认为他们对缩略图有很多答案,但我想添加一些其他网址来轻松获取youtube缩略图 . 我只是从Asaph的回答中得到一些文字 . 以下是获取youtube缩略图的一些网址

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

    对于高质量版本的缩略图,请使用与此类似的网址:

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

    还有一个中等质量版本的缩略图,使用类似于总部的网址:

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

    对于缩略图的标准定义版本,请使用与此类似的URL:

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

    对于缩略图的最大分辨率版本,请使用与此类似的URL:

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

    希望它能帮助不久的将来 .

  • 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;
    
  • 25

    YOUTUBE API VERSION 3 在2分钟内完成并运行

    如果你想要做的只是搜索YouTube并获得相关的属性:

    2.使用以下查询字符串 . 出于示例目的,url字符串中的搜索查询(由q =表示)是stackoverflow . 然后,YouTube会向您发送一个json回复,然后您可以解析缩略图,代码段,作者等 .

    https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&maxResults=50&q=stackoverflow&key=YOUR_API_KEY_HERE
    
  • 10

    我以这种方式使用了YouTube缩略图:

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

    请记住,YouTube阻止直接从其服务器中包含图像

  • 4027

    您可以使用YouTube Data API检索视频缩略图, Headers ,说明,评级,统计信息等 . API版本3需要密钥* . 获取密钥并创建videos: list请求:

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

    *您不仅需要密钥,还可能会要求您提供结算信息,具体取决于您计划进行的API请求的数量 . 但是,每天几百万的请求是免费的 .

    Source article .

  • 203

    另一个不错的选择是使用YouTube支持的oEmbed API .

    您只需将自己的YouTube网址添加到oEmbed网址,您就会收到一个JSON,其中包含缩略图和用于嵌入的HTML代码 .

    Example:

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

    会给你:

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

    阅读文档了解更多Information .

  • 11

    我为youtube缩略图创建的一个简单的php函数,类型是

    • 默认

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

    将文件另存为 .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>
    
  • 9

    使用此 - img.youtube.com/vi/YouTubeID/ImageFormat.jpg此处的图像格式与default,hqdefault,maxresdefault不同 .

  • 40

    在YouTube API V3中,我们还可以使用这些网址获取缩略图...它们会根据质量进行分类 .

    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
    

    并获得最大分辨率..

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

    在第一个答案中,这些URL相对于URL的一个优点是这些URL不会被防火墙阻止 .

  • 5

    我做了一个功能仅从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;
    }
    
  • -1

    这是我为获取缩略图而创建的一个简单函数,它易于理解和使用 . $ link是与浏览器完全相同的youtube链接,例如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;
    }
    
  • 10

    如果您正在使用公共API,那么最好的方法是使用if语句 .

    如果视频是公开的或不公开的,则使用url方法设置缩略图 . 如果视频是私有的,您可以使用api获取缩略图 .

    <?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';
    }
    
  • 9
    public const string tubeThumb = "http://i.ytimg.com/vi/[id]/hqdefault.jpg";
    vid.Thumbnail = tubeThumb.Replace("[id]", vid.VideoID);
    
  • 7
    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');
    
  • 0

    如果你想摆脱“黑条”并像YouTube一样去做,你可以使用:

    https://i.ytimg.com/vi_webp/<video id>/mqdefault.webp
    

    如果你不能使用 .webp 扩展,你可以这样做:

    https://i.ytimg.com/vi/<video id>/mqdefault.jpg
    

    此外,如果您需要非缩放版本,请使用 maxresdefault 而不是 mqdefault .

    注意:我'm not sure about the aspect ratio if you'重新计划使用 maxresdefault .

  • 5

    Top answer针对手动使用进行了优化 . 不带分隔符的视频ID令牌可以通过双击进行选择 .

    每个YouTube视频都有4个生成的图片 . 它们的格式可预测如下:

    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
    

    列表中的第一个是全尺寸图像,其他是缩略图图像 . 默认缩略图图像(即 1.jpg2.jpg3.jpg 之一)是:

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

    对于高质量版本的缩略图,请使用与此类似的网址:

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

    还有一个中等质量版本的缩略图,使用类似于总部的网址:

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

    对于缩略图的标准定义版本,请使用与此类似的URL:

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

    对于缩略图的最大分辨率版本,请使用与此类似的URL:

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

    所有上述网址都可通过http获取 . 此外,略短的主机名 i3.ytimg.com 代替上面的示例网址中的 img.youtube.com .

    或者,您可以使用YouTube Data API (v3)获取缩略图图像 .

  • 66

    YouTube由谷歌拥有,谷歌喜欢为不同的屏幕尺寸提供合理数量的图像,因此它的图像以不同的尺寸存储,下面是您喜欢的缩略图的示例

    低质量缩略图:

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

    中等质量缩略图:

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

    高品质缩略图:

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

    最高质量缩略图:

    http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg
    
  • 47

    Method 1:

    你可以在json页面找到youtube video所有信息,甚至"thumbnail_url" http://www.youtube.com/oembed?format=json&url= {你的视频网址就在这里}

    像最终的网址看php测试代码

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

    产量

    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
    

    有关详细信息,您还可以查看https://www.youtube.com/watch?v=mXde7q59BI8视频教程1

    Method 2: 使用youtube img链接https://img.youtube.com/vi/ "insert-youtube-video-id-here" /default.jpg

    Method 3: 使用浏览器源代码获取缩略图使用视频网址链接-go到视频源代码并搜索thumbnailurl现在您可以将此网址用于您的代码:{img src = "https://img.youtube.com/vi/" insert-youtube-video-id-here "/default.jpg"}

    有关详细信息,您还可以查看http://hzonesp.com/php/get-youtube-video-thumbnail-using-id/https://www.youtube.com/watch?v=9f6E8MeM6PI视频教程2

  • 26

    只是为了添加/扩展所给出的解决方案,我觉得有必要注意,因为我自己有这个问题,实际上可以通过一个HTTP请求获取多个YouTube视频内容,在这种情况下,缩略图:

    使用Rest Client,在本例中为HTTPFUL,您可以执行以下操作:

    <?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);
    
    ?>
    
  • 20

    每个YouTube视频都有4个生成的图片 . 它们的格式可预测如下:

    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
    

    列表中的第一个是全尺寸图像,其他是缩略图图像 . 默认缩略图图像(即 1.jpg2.jpg3.jpg 之一)是:

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

    对于高质量版本的缩略图,请使用与此类似的网址:

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

    还有一个中等质量版本的缩略图,使用类似于总部的网址:

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

    对于缩略图的标准定义版本,请使用与此类似的URL:

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

    对于缩略图的最大分辨率版本,请使用与此类似的URL:

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

    所有上述网址都可通过http获取 . 此外,略短的主机名 i3.ytimg.com 代替上面的示例网址中的 img.youtube.com .

    或者,您可以使用YouTube Data API (v3)获取缩略图图像 .

  • 6

    如果您想从YouTube获取特定视频ID的最大图片,那么网址应如下所示:

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

    使用API,您可以选择默认缩略图图像 . 简单的代码应该是这样的:

    //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);
    
  • 0

    这是我的客户端唯一无需API密钥的解决方案 .

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

    代码:

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

    YouTube Data API v3中,您可以使用videos->list功能获取视频的缩略图 . 从snippet.thumbnails.(key)开始,您可以选择默认,中等或高分辨率缩略图,并获取其宽度,高度和URL .

    您还可以使用thumbnails->set功能更新缩略图 .

    例如,您可以查看YouTube API Samples项目 . (PHP ones . )

  • 0

    我找到了这个漂亮的工具,可让您使用放置在图像上方的YouTube播放按钮创建图像:

  • 0

    使用:

    https://www.googleapis.com/youtube/v3/videoCategories?part=snippet,id&maxResults=100&regionCode=us&key=**Your YouTube ID**
    

    以上是链接 . 使用它,您可以找到视频的YouTube特征 . 找到特征后,您可以获取所选类别的视频 . 之后,您可以使用Asaph's answer找到所选的视频图像 .

    尝试上述方法,您可以解析YouTube API中的所有内容 .

相关问题