如果我有一个YouTube视频URL,有没有任何方法可以使用PHP和cURL从YouTube API获取相关的缩略图?
当前回答
这是我的客户端唯一不需要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
},
{})
}
其他回答
这里是我为获取缩略图创建的一个简单函数。它易于理解和使用。
$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;
}
这是我的客户端唯一不需要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
},
{})
}
您可以使用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
如果您使用的是公共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';
}
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');
推荐文章
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- PHP字符串中的花括号
- PHP -如何最好地确定当前调用是否来自CLI或web服务器?
- 无法打开流:没有这样的文件或目录
- 在php中生成一个随机密码