如果我有一个YouTube视频URL,有没有任何方法可以使用PHP和cURL从YouTube API获取相关的缩略图?
当前回答
在YouTube Data API v3中,您可以使用videos->list函数获取视频的缩略图。从snippet.t缩略图.(key)中,您可以选择默认、中等或高分辨率缩略图,并获取其宽度、高度和URL。
您还可以使用缩略图->设置功能更新缩略图。
例如,您可以查看YouTube API示例项目。(PHP版本。)
其他回答
虽然已经有很多答案,但对于新访客,我会留下两个获取缩略图的选项。
通过YouTube数据API获取缩略图
在Google Cloud Platform注册应用程序并激活YouTube Data API v3库在凭据部分创建API密钥。这样您将获得访问API的密钥并发送有关视频信息的请求,包括获取缩略图。
$api_key = 'YOUR_API_KEY';
$youtube_video_id = 'jNQXAC9IVRw';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://www.googleapis.com/youtube/v3/videos?key='.$api_key.'&part=snippet&id='.$youtube_video_id,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response,true);
print_r($response); // result with video information and thumbnails
从没有API的直接链接获取缩略图
除了API之外,还可以通过直接链接获取缩略图,如下所示:
https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg
让我们详细考虑一下这个选项:
https://i.ytimg.com/vi/<YOUTUBE_VIDEO_ID>/<SIZE_VALUE>.jpg
哪里:
YOUTUBE_VIDEO_ID:您的视频IDSIZE_VALUE:缩略图大小。变量可以包含以下值:default、mqdefault、hqdefault、sddefault、maxresdefault
$youtube_video_id = 'jNQXAC9IVRw';
$size = 'hqdefault';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://i.ytimg.com/vi/{$youtube_video_id}/{$size}.jpg",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
// Write the file
$handle = fopen("image/filename.jpg", 'w'); // set your directory and filename
fwrite($handle, $response);
fclose($handle);
阿萨夫说的是对的。然而,并不是每个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
您可以找到JavaScript和PHP脚本来检索缩略图和其他YouTube信息:
如何使用PHP获取YouTube视频信息使用JavaScript检索YouTube视频详细信息-JSON和API v2
您还可以使用YouTube视频信息生成器工具获取所有通过提交URL或视频id来获取关于YouTube视频的信息。
以下是针对手动使用而优化的最佳答案。无分隔符的视频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数据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
},
{})
}
如果你想要YouTube上某个特定视频ID的最大图片,那么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);
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- PHP中的echo, print和print_r有什么区别?
- 在Bash中将输出赋给变量
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 从IP地址获取位置
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?
- 当使用Composer的开发/生产开关时,如何正确部署?