如果我有一个YouTube视频网址,是否有任何方式使用PHP和卷,以获得相关的缩略从YouTube API?

有帮助吗?

解决方案

每个YouTube视频的具有四个生成的图像。它们可预测格式如下:

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

有关的缩略图的高质量版本使用类似下面的URL:

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

还有缩略图的中等质量的版本,使用类似于HQ的URL:

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

所有上述URL的是可通过HTTP太。此外,该稍短主机名i3.ytimg.com工作代替img.youtube.com的在上面的例子中的URL。

另外,您也可以使用 YouTube数据API(V3)获得缩略图。

其他提示

您可以使用 YouTube数据API 检索视频缩略图,标题,描述,分类,统计和更多。 API版本3需要密钥*。获取密钥,并创建一个视频:列表 请求:

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

示例PHP代码

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

<强>输出

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请求的数量信息。然而,每天几百万的请求都是免费的。

源文章

什么阿瑟夫说是正确的。然而,不是每个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 and PHP scripts检索的略图和其他 YouTube上的信息:

你也可以使用 YouTube上的视频信息生成器 工具,以获得的所有信息YouTube视频通过提交一个网址或视频身份证。

在YouTube的API V3我们也可以利用这些URL获得缩略图...它们分别基于其质量。

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应该是这样的:

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

如果你想摆脱“黑网吧”,并做到这一点像YouTube这样做,你可以使用:

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

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

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

另外,如果你需要的未缩放版本,使用maxresdefault代替mqdefault

请注意:我不知道关于宽高比,如果你打算使用maxresdefault

我提出的功能,只有来自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;
}

YouTube数据API V3 ,你可以得到视频的缩略图用的 videos->列表功能。从 snippet.thumbnails。(键) ,你可以选择默认,中等或高分辨率的缩略图,并获得它的宽度,高度和网址。

您还可以更新与 thumbnails->设置功能缩略图

有关实施例中,可以检查出该的YouTube API样品的项目。 ( PHP那些的。)

您可以获取其中包含的URL 视频输入到该视频的缩略图。还有在链接的示例代码。或者,如果你想解析XML,有信息 rel="noreferrer">。返回的XML具有media:thumbnail元素,它包含缩略图的URL。

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

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

使用:

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

上面是链接。利用这一点,你可以找到的视频在YouTube的特点。找到后特性,你可以得到所选类别的视频。在此之后,你可以使用的亚萨的回答 的。

试试上面的方法,你可以从YouTube的 API

解析一切

我已经使用的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防止直接从他们的服务器包括图像。

我发现这个漂亮的工具,可用于创建图像带在YouTube玩按钮放过图像:

我想补充/扩展给出的解决方案,我觉得这是需要注意的是,因为我有这个问题我自己,一个可以真正抓住多个YouTube视频内容,在这种情况下,缩略图,用一个HTTP请求:

使用REST客户端,在这种情况下,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);

?>

另一种很好的替代方案将是使用其通过YouTube支援透过oEmbed API。

您只需将您的YouTube网址添加到URL透过oEmbed,您会收到包括缩略图和嵌入HTML代码中的JSON。

示例:

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
}

阅读更多信息中的文档。

一个简单的PHP function我创造的YouTube的缩略和类型

  • 默认的
  • 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;}

如果您使用的是公共API,最好的办法就是使用 if 发言。

如果视频是公共或非上市,你设置的缩略用网址的方法。如果视频是私人使用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';
    }

YouTube数据API

YouTube为我们提供了四个产生图像的每一个视频通过数据API(v3),例如,

  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

获得的图像通过API

  1. 首先得到你的公共API关键在 谷歌API控制台.
  2. 为每个YouTube的缩略参考 API文件, 你需要访问的资源段。缩略图。
  3. 按这个,你需要那句你的URL喜欢这个-

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

现在改变你的视频ID和API关键你们各自的视频-id和api-关键和其的反应将是一个JSON输出提供的四个环节中的缩略图片段变量(如果是所有可用)。

您可以用得到YouTube视频的网址视频ID parse_url parse_str 并然后插入在用于图像预测网址。由于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://tools.tutsplanet.com/index.php /获取-的YouTube视频-缩略图

我觉得自己是一个很多答案缩略图,但我想添加一些其他的URL获得YouTube的缩略图很容易。我只是把从亚萨的回答一些文字。这里有一些网址,让YouTube缩略图:

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

有关的缩略图的高质量版本使用类似下面的URL:

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

还有缩略图的中等质量的版本,使用类似于高品质的URL:

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

顶部答案是手动使用进行了优化。无隔板的视频ID令牌使选择与双击。

每个YouTube视频的具有四个生成的图像。它们可预测格式如下:

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

有关的缩略图的高质量版本使用类似下面的URL:

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

还有缩略图的中等质量的版本,使用类似于HQ的URL:

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

所有上述URL的是可通过HTTP太。此外,该稍短主机名i3.ytimg.com工作代替img.youtube.com的在上面的例子中的URL。

另外,您也可以使用 YouTube数据API(V3)获得缩略图

<强>方法1:

您可以找到YouTube视频与更是把“thumbnail_url”一个JSON页的所有信息, http://www.youtube.com/oembed?format=json&url= {您的视频网址放在这里}

像最终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

<强>方法2:

使用的YouTube图像链接, https://img.youtube.com/vi/ “嵌入的YouTube视频-ID-这里“/default.jpg

<强>方法3:

使用浏览器的源代码用于使用视频URL链接获取缩略图 - 进入视频源代码和搜索thumbnailurl。 现在你可以使用这个网址为 源代码:

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

有关详细信息,你还可以看到的 如何获得使用ID YouTube视频缩略图 的 要么 https://www.youtube.com/watch?v=9f6E8MeM6PI 视频教程2

使用img.youtube.com/vi/YouTubeID/ImageFormat.jpg

下面的图像格式是默认等不同,hqdefault, maxresdefault。

这是我的客户端仅无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`

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

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

下面是我用于获取缩略图创建了一个简单函数。这是很容易理解和使用。

$链路是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;
}

保存在空PHP文件此代码并对其进行测试。

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

感谢。

public const string tubeThumb = "http://i.ytimg.com/vi/[id]/hqdefault.jpg";
vid.Thumbnail = tubeThumb.Replace("[id]", vid.VideoID);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top