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


当前回答

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

其他回答

另一个好的选择是使用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"
}

有关详细信息,请阅读文档。

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

我认为缩略图有很多答案,但我想添加一些其他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

使用img.youtube.com/vi/YouTubeID/ImageFormat.jpg

这里的图像格式不同,最大默认值。

虽然已经有很多答案,但对于新访客,我会留下两个获取缩略图的选项。

通过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);