如果我有一个 YouTube 视频 URL,有没有办法使用 PHP 和 cURL 从 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.jpg
、2.jpg
、3.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
代替了上述示例 URL 中的 img.youtube.com
。
或者,您可以使用 YouTube Data API (v3) 获取缩略图。
您可以使用 YouTube Data API 检索视频缩略图、标题、说明、评级、统计信息等。 API 版本 3 需要密钥*。获取密钥并创建 videos: list 请求:
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 请求数量要求您提供计费信息。但是,每天有几千个请求是免费的。
jsonc
而不是 json
。由于您的 JSON 结构错误,它失败了。
jsonc
。 jQuery 和 PHP 示例必须使用 json
。我已经更新了代码以符合新的 JSON 结构。我现在正在使用该代码,并且它正在实时工作。所以不要说不阅读更改就行不通。谢谢!
v=2
) 会处理 API 更改。
亚萨说的是对的。但是,并非每个 YouTube 视频都包含所有九个缩略图。此外,缩略图的图像大小取决于视频(以下数字基于一个)。有一些缩略图保证存在:
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
此外,其他一些缩略图可能存在也可能不存在。他们的存在可能是基于视频是否高质量。
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
您可以在以下位置找到用于检索缩略图和其他 YouTube 信息的 JavaScript 和 PHP 脚本:
如何使用 PHP 获取 YouTube 视频信息
使用 JavaScript 检索 YouTube 视频详细信息 - JSON & API v2
您还可以使用 YouTube Video Information Generator 工具通过提交 URL 或视频 ID 来获取有关 YouTube 视频的所有信息。
mqdefault.jpg
为 320x180
在 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 的一个优点是这些 URL 不会被防火墙阻止。
如果您想摆脱“黑条”并像 YouTube 那样做,您可以使用:
https://i.ytimg.com/vi_webp/<video id>/mqdefault.webp
如果您不能使用 .webp
文件扩展名,您可以这样做:
https://i.ytimg.com/vi/<video id>/mqdefault.jpg
此外,如果您需要未缩放的版本,请使用 maxresdefault
而不是 mqdefault
。
注意:如果您打算使用 maxresdefault
,我不确定纵横比。
sddefault
? img.youtube.com/vi_webp/dQw4w9WgXcQ/sddefault.webp 不断返回带有黑条的图像。
如果您想要某个特定视频 ID 的 YouTube 上最大的图片,那么 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 获取现有图像
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;
}
您可以获得包含视频缩略图 URL 的 Video Entry。链接中有示例代码。或者,如果您想解析 XML,则有信息 here。返回的 XML 有一个 media:thumbnail
元素,其中包含缩略图的 URL。
在 YouTube Data API v3 中,您可以使用 videos->list 函数获取视频的缩略图。从 snippet.thumbnails.(key),您可以选择默认、中等或高分辨率缩略图,并获取其宽度、高度和 URL。
您还可以使用 thumbnails->set 功能更新缩略图。
例如,您可以查看 YouTube API Samples 项目。 (PHP ones。)
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
// 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 API 第 3 版在 2 分钟内启动并运行
如果您只想搜索 YouTube 并获取相关属性:
获取一个公共 API——这个链接给出了一个很好的方向使用下面的查询字符串。出于示例目的,URL 字符串中的搜索查询(由 q= 表示)是 stackoverflow。然后,YouTube 将向您发送一个 JSON 回复,您可以在其中解析缩略图、片段、作者等。 https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&maxResults=50&q=stackoverflow&key=YOUR_API_KEY_HERE
另一个不错的选择是使用 YouTube 支持的 oEmbed API。
您只需将您的 YouTube URL 添加到 oEmbed URL,您就会收到一个 JSON,其中包括一个缩略图和用于嵌入的 HTML 代码。
例子:
http://www.youtube.com/oembed?format=json&url=http%3A//youtube.com/watch%3Fv%3DxUeJdWYdMmQ
会给你:
{
"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"
}
阅读文档以了解更多信息information。
YouTube 正在从 2 个服务器提供缩略图。您只需将
https://img.youtube.com https://i.ytimg.com
示例以 https://i.ytimg.com 服务器为例,只是因为它更短,没有其他特殊原因。您可以同时使用两者。
播放器背景缩略图 (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
视频帧缩略图 (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
最低质量的缩略图 (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
中等质量缩略图 (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
高品质缩略图 (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
标准质量缩略图 (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
未缩放的缩略图分辨率
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
您可以使用 parse_url、parse_str 从 YouTube 视频 URL 获取视频 ID,然后将其插入图像的预测 URL。感谢 YouTube 提供的预测 URL
$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";
您可以使用此工具生成 YouTube 缩略图
https://youtube-thumbnail-tool.com
利用:
https://www.googleapis.com/youtube/v3/videoCategories?part=snippet,id&maxResults=100®ionCode=us&key=**Your YouTube ID**
上面是链接。使用它,您可以找到视频的 YouTube 特征。找到特征后,您可以获取所选类别的视频。之后,您可以使用 Asaph's answer 找到选定的视频图像。
尝试上述方法,您可以解析 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 禁止直接包含来自其服务器的图像。
只是为了添加/扩展给定的解决方案,我觉得有必要注意,因为我自己也遇到了这个问题,实际上可以通过一个 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);
?>
YouTube 数据 API
YouTube 通过 Data API (v3) 为每个视频提供了四个生成的图像,例如,
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 控制台获取您的公共 API 密钥。根据 API 文档中 YouTube 的缩略图参考,您需要访问 snippet.thumbnails 上的资源。根据这个,您需要像这样描述您的网址 - www.googleapis.com/youtube/v3/videos?part=snippet&id=`yourVideoId`&key=`yourApiKey`
现在将您的视频 ID 和 API 密钥更改为您各自的 video-id 和 api-key,其响应将是 JSON 输出,为您提供片段变量缩略图中的四个链接(如果全部可用)。
我发现了这个漂亮的工具,它允许您使用放置在图像上的 YouTube 播放按钮来创建图像:
安装在服务器上进行脚本编写:https://github.com/halgatewood/youtube-thumbnail-enhancer
我为 YouTube 缩略图创建的一个简单的 PHP 函数,类型是
默认
hqdefault
MQ默认
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
语句。
如果视频是公开的或不公开的,您可以使用 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> Unlisted';
}
elseif($video_status == 'public'){
$video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
$video_status = '<i class="fa fa-eye"></i> Public';
}
elseif($video_status == 'private'){
$video_thumbnail = $playlistItem['snippet']['thumbnails']['maxres']['url'];
$video_status = '<i class="fa fa-lock"></i> Private';
}
我认为缩略图有很多答案,但我想添加一些其他 URL 以非常轻松地获取 YouTube 缩略图。我只是从 Asaph 的回答中获取一些文字。以下是一些获取 YouTube 缩略图的 URL:
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
方法一:
您可以找到带有 JSON 页面的 YouTube 视频的所有信息,该页面甚至包含“thumbnail_url”,http://www.youtube.com/oembed?format=json&url={your video URL goes here}
喜欢最终 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
有关详细信息,您还可以查看 How to get a YouTube video thumbnail using id 或 https://www.youtube.com/watch?v=mXde7q59BI8 视频教程 1
方法二:
使用 YouTube 图片链接,https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg
方法三:
使用浏览器源代码通过视频 URL 链接获取缩略图 - 转到视频源代码并搜索 thumbnailurl。现在您可以在源代码中使用此 URL:
{img src="https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg"}
有关详细信息,您还可以查看 How to get a YouTube video thumbnail using id 或 https://www.youtube.com/watch?v=9f6E8MeM6PI 视频教程 2
https://www.youtube.com/watch?v=mXde7q59BI8
和 https://www.youtube.com/watch?v=9f6E8MeM6PI
(实际上)已损坏。
https://i.ytimg.com/vi/<--Video ID-->/default.jpg
图片尺寸 重量 120px 高度 90px
https://i.ytimg.com/vi/<--Video ID-->/mqdefault.jpg
图片尺寸 重量 320px 高度 180px
https://i.ytimg.com/vi/<--Video ID-->/hqdefault.jpg
图片尺寸 重量 480px 高度 360px
https://i.ytimg.com/vi/<--Video ID-->/sddefault.jpg
图片尺寸 重量 640px 高度 480px
https://i.ytimg.com/vi/<--Video ID-->/maxresdefault.jpg
图片尺寸 重量 1280px 高度 720px
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');
这里的the top answer针对手动使用进行了优化。不带分隔符的视频 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.jpg
、2.jpg
、3.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
代替了上述示例 URL 中的 img.youtube.com
。
或者,您可以使用 YouTube Data API (v3) 获取缩略图。
这是我的仅客户端不需要 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
},
{})
}
使用img.youtube.com/vi/YouTubeID/ImageFormat.jpg
这里的图像格式不同,例如 default、hqdefault、maxresdefault。
将此代码保存在 empty.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';
}
有一些缩略图保证存在:
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
谢谢。
http://www.img.youtube.com
,只能使用http://img.youtube.com
sddefault.jpg
和maxresdefault.jpg
格式不再有效sddefault
和maxresdefault
并不总是可用的。mqdefault
是否适用于所有视频?获得没有 2 个黑色边框(顶部和底部)的缩略图的最佳 URL 是什么?maxres2.jpg
、hq2.jpg
、hq3.jpg
等。