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


当前回答

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

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

其他回答

如果你想要YouTube上某个特定视频ID的最大图片,那么URL应该是这样的:

http://i3.ytimg.com/vi/SomeVideoIDHere/0.jpg

使用API,您可以获取默认缩略图图像。简单代码应该是这样的:

//Grab the default thumbnail image
$attrs = $media->group->thumbnail[1]->attributes();
$thumbnail = $attrs['url'];
$thumbnail = substr($thumbnail, 0, -5);
$thumb1 = $thumbnail."default.jpg";

// Grab the third thumbnail image
$thumb2 = $thumbnail."2.jpg";

// Grab the fourth thumbnail image.
$thumb3 = $thumbnail."3.jpg";

// Using simple cURL to save it your server.
// You can extend the cURL below if you want it as fancy, just like
// the rest of the folks here.

$ch = curl_init ("$thumb1");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata = curl_exec($ch);
curl_close($ch);

// Using fwrite to save the above
$fp = fopen("SomeLocationInReferenceToYourScript/AnyNameYouWant.jpg", 'w');

// Write the file
fwrite($fp, $rawdata);

// And then close it.
fclose($fp);

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

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

YouTube归谷歌所有,谷歌喜欢为不同的屏幕大小提供合理数量的图像,因此其图像以不同的大小存储。下面是缩略图的示例:

低质量缩略图:

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

中等质量缩略图:

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

高质量缩略图:

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

最高质量缩略图:

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

如果您使用的是公共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>&nbsp;Unlisted';
    }
    elseif($video_status == 'public'){
        $video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
        $video_status = '<i class="fa fa-eye"></i>&nbsp;Public';
    }
    elseif($video_status == 'private'){
        $video_thumbnail = $playlistItem['snippet']['thumbnails']['maxres']['url'];
        $video_status = '<i class="fa fa-lock"></i>&nbsp;Private';
    }

为了添加/扩展所给出的解决方案,我觉得有必要注意到,正如我自己遇到的问题一样,实际上可以通过一个HTTP请求抓取多个YouTube视频内容,在本例中是缩略图:

使用Rest Client(在本例中为HTTPFUL),您可以执行以下操作:

<?php
header("Content-type", "application/json");

//download the httpfull.phar file from http://phphttpclient.com
include("httpful.phar");

$youtubeVidIds= array("nL-rk4bgJWU", "__kupr7KQos", "UCSynl4WbLQ", "joPjqEGJGqU", "PBwEBjX3D3Q");


$response = \Httpful\Request::get("https://www.googleapis.com/youtube/v3/videos?key=YourAPIKey4&part=snippet&id=".implode (",",$youtubeVidIds)."")

->send();

print ($response);

?>