获取 YouTube 视频缩略图并将其与 PHP 一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32346276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:55:22  来源:igfitidea点击:

Get YouTube video thumbnail and use it with PHP

phpapiyoutubeyoutube-apivideo-thumbnails

提问by Ron

How can I access thumbnail collection of a YouTube video using the link of the video from the YouTube API. I want thumbnails to be displayed on website using PHP using the video id stored in a variable for example $link

如何使用来自 YouTube API 的视频链接访问 YouTube 视频的缩略图集合。例如,我希望使用存储在变量中的视频 ID 使用 PHP 在网站上显示缩略图$link

回答by Ron

YouTube stores many different types of thumbnails on its server for different devices. You can access it by using the video id which every YouTube video has. You can display the images on your website using a variable $linkwhich holds the id of the video and substituting it in the place for video_ID in the link.

YouTube 在其服务器上为不同设备存储了许多不同类型的缩略图。您可以使用每个 YouTube 视频都有的视频 ID 来访问它。您可以使用$link保存视频 ID 的变量在您的网站上显示图像,并将其替换为链接中 video_ID 的位置。

Low quality thumbnail:

低质量缩略图:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg

Medium quality thumbnail:

中等质量缩略图:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg

High quality thumbnail:

高质量缩略图:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg

Maximum quality thumbnail:

最高质量缩略图:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg

Example:

例子:

If you want to access the thumbnail of the following video:

如果您想访问以下视频的缩略图:

https://www.youtube.com/watch?v=Q-GYwhqDo6o

Video ID : Q-GYwhqDo6o

视频编号: Q-GYwhqDo6o

So, this is how video thumbnail link looks like:

所以,这就是视频缩略图链接的样子:

http://img.youtube.com/vi/Q-GYwhqDo6o/mqdefault.jpg

Hope it helps. Enjoy coding.

希望能帮助到你。享受编码。

回答by Rishi

To get high-quality image you can use the following URL which is fetched from youtube API

要获得高质量的图像,您可以使用从 youtube API 获取的以下 URL

$video_id = explode("?v=", $link);
$video_id = $video_id[1];
$thumbnail="http://img.youtube.com/vi/".$video_id."/maxresdefault.jpg";

回答by Kamal Sanghavi

You can use the below code. It is work for me. Choose the image quality as per your requirement.

您可以使用以下代码。这对我来说是工作。根据您的要求选择图像质量。

<?php
$youtubeID = getYouTubeVideoId('youtube video url');
$thumbURL = 'https://img.youtube.com/vi/' . $youtubeID . '/mqdefault.jpg';
print_r($thumbURL);

function getYouTubeVideoId($pageVideUrl) {
    $link = $pageVideUrl;
    $video_id = explode("?v=", $link);
    if (!isset($video_id[1])) {
        $video_id = explode("youtu.be/", $link);
    }
    $youtubeID = $video_id[1];
    if (empty($video_id[1])) $video_id = explode("/v/", $link);
    $video_id = explode("&", $video_id[1]);
    $youtubeVideoID = $video_id[0];
    if ($youtubeVideoID) {
        return $youtubeVideoID;
    } else {
        return false;
    }
}
?>

回答by Manojkiran.A

here is my handy function to download the Youtube thumbnail image

这是我下载 Youtube 缩略图的方便功能

function downloadYouTubeThubnailImage($youTubeLink='',$thumbNamilQuality='',$fileNameWithExt='',$fileDownLoadPath='')
    {
        $videoIdExploded = explode('?v=', $youTubeLink);   

        if ( sizeof($videoIdExploded) == 1) 
        {
            $videoIdExploded = explode('&v=', $youTubeLink);

            $videoIdEnd = end($videoIdExploded);

            $removeOtherInVideoIdExploded = explode('&',$videoIdEnd);

            $youTubeVideoId = current($removeOtherInVideoIdExploded);
        }else{
            $videoIdExploded = explode('?v=', $youTubeLink);

            $videoIdEnd = end($videoIdExploded);

            $removeOtherInVideoIdExploded = explode('&',$videoIdEnd);

            $youTubeVideoId = current($removeOtherInVideoIdExploded);
        }

        switch ($thumbNamilQuality) 
        {
            case 'LOW':
                    $imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/sddefault.jpg';
                break;

            case 'MEDIUM':
                    $imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/mqdefault.jpg';
                break;

            case 'HIGH':
                    $imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/hqdefault.jpg';
                break;

            case 'MAXIMUM':
                    $imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/maxresdefault.jpg';
                break;
            default:
                return  'Choose The Quality Between [ LOW (or) MEDIUM  (or) HIGH  (or)  MAXIMUM]';
                break;
        }  

        if( empty($fileNameWithExt) || is_null($fileNameWithExt)  || $fileNameWithExt === '') 
        {
            $toArray = explode('/',$imageUrl);
            $fileNameWithExt = md5( time().mt_rand( 1,10 ) ).'.'.substr(strrchr(end($toArray),'.'),1);
          }

          if (! is_dir($fileDownLoadPath)) 
            {
                mkdir($fileDownLoadPath,0777,true);
            }

            file_put_contents($fileDownLoadPath.$fileNameWithExt, file_get_contents($imageUrl));
            return $fileNameWithExt;   
    }

Function Description

Function Description

Argumemts

论据

$youTubeLinkYoutube url for examplehttps://www.youtube.com/watch?v=a3ICNMQW7Ok

$youTubeLink优酷网址 for examplehttps://www.youtube.com/watch?v=a3ICNMQW7Ok

$thumbNamilQualityIt has Many Quality Such as LOW ,MEDIUM, HIGH, MAXIMUM

$thumbNamilQuality它有许多品质,例如 LOW ,MEDIUM, HIGH, MAXIMUM

Thumbnail Quality list Taken from https://stackoverflow.com/a/32346348/8487424

缩略图质量列表取自 https://stackoverflow.com/a/32346348/8487424

&& https://stackoverflow.com/a/47546113/8487424

&& https://stackoverflow.com/a/47546113/8487424

$fileNameWithExtFile Name with Extension**for example** myfavouriteimage.png

$fileNameWithExt带扩展名的文件名** for example** myfavouriteimage.png

NOTE $fileNameWithExtis not mandatory it will generate the uuidbased file name for Example91b2a30d0682058ebda8d71606f5e327.jpg

注意 $fileNameWithExt不是强制性的,它会uuidExample91b2a30d0682058ebda8d71606f5e327.jpg

if you want to put the file to the custom directory use this argument

如果要将文件放入自定义目录,请使用此参数

NOTE $fileDownLoadPathis not mandatory it will generate the image file where the script is executing

注意 $fileDownLoadPath不是强制性的,它会生成脚本正在执行的图像文件

Some of the sample examples

一些示例示例

$folderpath = 'c:'.DIRECTORY_SEPARATOR.'xampp'.DIRECTORY_SEPARATOR.'htdocs'.DIRECTORY_SEPARATOR.'youtube'.DIRECTORY_SEPARATOR;

$imageName = 'mybeautfulpic.jpg';

downloadYouTubeThubnailImage('https://www.youtube.com/watch?v=a3ICNMQW7Ok','MAXIMUM',null,$folderpath );

downloadYouTubeThubnailImage('https://www.youtube.com/watch?v=a3ICNMQW7Ok','LOW',$imageName ,null);

Hope it is answered already but this function has some exta features

希望它已经得到回答,但这个功能有 some exta features

回答by kdelinx

Google changed API on v.3 and those code from Python work exactly! You can use for PHP.

Google 在 v.3 上更改了 API,Python 中的那些代码完全可以正常工作!您可以用于 PHP。

def get_small_image_url(self):
    return 'http://img.youtube.com/vi/%s/%s.jpg' % (self.video_id, random.randint(1, 3))

def get_hqdefault(self):
    return 'http://i1.ytimg.com/vi/%s/hqdefault.jpg' % self.video_id

def get_mqdefault(self):
    return 'http://i1.ytimg.com/vi/%s/mqdefault.jpg' % self.video_id

def get_sddefault(self):
    return 'http://i1.ytimg.com/vi/%s/sddefault.jpg' % self.video_id

def get_video_id(self, url):
    link = urlparse.urlparse(url)
    if link.hostname == 'youtu.be':
        return link.path[1:]
    if link.hostname in ('www.youtube.com', 'youtube.com'):
        if link.path == '/watch':
            state = urlparse.parse_qs(link.query)
            return state['v'][0]
        if link.path[:7] == '/embed/':
            return link.path.split('/')[2]
        if link.path[:3] == '/v/':
            return link.path.split('/')[2]
    return False

def get_meta(self, video_id):
    api_token = **'here your API_Token'**
    url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&id=%s&key=%s' % (video_id, api_token)
    response = json.load(urllib.urlopen(url))
    print response
    context = {
        'title': response['items'][0]['snippet']['localized']['title'],
        'desc': response['items'][0]['snippet']['localized']['description']
    }
    return context

def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
    video_id = self.get_video_id(self.url)
    meta = self.get_meta(video_id)
    self.video_id = video_id
    self.title = meta['title']
    self.description = meta['desc']
    super(Videos, self).save(
        force_insert=force_insert,
        force_update=force_update,
        using=using,
        update_fields=update_fields
    )