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


当前回答

如果你想摆脱“黑条”,像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 Data API v3中,您可以使用videos->list函数获取视频的缩略图。从snippet.t缩略图.(key)中,您可以选择默认、中等或高分辨率缩略图,并获取其宽度、高度和URL。

您还可以使用缩略图->设置功能更新缩略图。

例如,您可以查看YouTube API示例项目。(PHP版本。)

YouTube正在从两个服务器提供缩略图。你只需要用你自己的YouTube视频ID替换<YouTube_Video_ID_HERE>。如今,由于图像尺寸较小,webP是快速加载图像的最佳格式。

https://img.youtube.comhttps://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
// 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

这是我的客户端唯一不需要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
    },
    {})
}