如果我有一个YouTube视频URL,有没有任何方法可以使用PHP和cURL从YouTube API获取相关的缩略图?


当前回答

在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不会被防火墙阻止。

其他回答

这是我的客户端唯一不需要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获取现有图像

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

我认为缩略图有很多答案,但我想添加一些其他URL,以便非常容易地获得YouTube缩略图。我只是从亚萨的回答中提取一些文字。以下是获取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

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