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 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 $link which holds the id of the video and substituting it
in the place for video_ID in the link.
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
So, this is how video thumbnail link looks like:
http://img.youtube.com/vi/Q-GYwhqDo6o/mqdefault.jpg
Hope it helps. Enjoy coding.
To get high-quality image you can use the following URL which is fetched from youtube API
$video_id = explode("?v=", $link);
$video_id = $video_id[1];
$thumbnail="http://img.youtube.com/vi/".$video_id."/maxresdefault.jpg";
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;
}
}
?>
here is my handy function to download the Youtube thumbnail image
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
Argumemts
$youTubeLink Youtube url for example https://www.youtube.com/watch?v=a3ICNMQW7Ok
$thumbNamilQuality It has Many Quality Such as LOW ,MEDIUM, HIGH, MAXIMUM
Thumbnail Quality list Taken from
https://stackoverflow.com/a/32346348/8487424
&&
https://stackoverflow.com/a/47546113/8487424
$fileNameWithExt File Name with Extension**for example** myfavouriteimage.png
NOTE $fileNameWithExt is not mandatory it will generate the uuid based file name
for Example 91b2a30d0682058ebda8d71606f5e327.jpg
if you want to put the file to the custom directory use this argument
NOTE $fileDownLoadPath is not mandatory it will generate the image file where the script is executing
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
Google changed API on v.3 and those code from Python work exactly! You can use for 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
)
the simplest and easiest way to get youtube-video-id from a youtube link using str_replace.
$youtube_ids = str_replace("https://www.youtube.com/watch?v=", "", "https://www.youtube.com/watch?v=QBKdaUv5YaI");
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/maxresdefault.jpg';
Low-quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/sddefault.jpg';
Medium quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/mqdefault.jpg';
High quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/hqdefault.jpg';
Maximum quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/maxresdefault.jpg';
Related
I'm working on a web application that allow users to post any Youtube videos to their profile or pages they manages. This is the code that I use to post Youtube video to my profile
$videoUpload = $fb->post('/me/videos', ['description' => 'example description', 'file_url' => 'https://r2---sn-npoeene7.googlevideo.com/videoplayback?pl=24&lmt=1513082002389285&id=o-AIPnl4v8svvYBTFPYwJOsRanE_5O8YSK0F3bMkTqN6QR&itag=22&signature=8051FCC4C243296224CD1D7ADB4E5C0A90125C57.66FF9FF2063C3A8F00F143FB51BB3E98F7AEBB7B&requiressl=yes&ip=203.189.156.104&sparams=dur,ei,expire,id,initcwndbps,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pl,ratebypass,requiressl,source&key=cms1&mime=video%2Fmp4&dur=301.952&fvip=2&ipbits=0&c=WEB&expire=1519648901&ratebypass=yes&ei=JayTWtSaDcWqoQORionoCg&source=youtube&redirect_counter=1&cm2rm=sn-jvbxuxavoapox-2oil7e&fexp=23712580&req_id=21384f45d53ba3ee&cms_redirect=yes&mm=29&mn=sn-npoeene7&ms=rdu&mt=1519627218&mv=m'], $access_token);
$videoUpload = $videoUpload->getGraphNode()->asArray();
The problem is that Facebook not allow to post Youtube link directly, so I need to generate a downloadable link from that video in order to post to Facebook.
Here is the PHP code that use to generate a download link from a Youtube video
<?php
$id = 'RllJtOw0USI';
if (isset($_GET["id"]))
$id = $_GET["id"];
parse_str(file_get_contents('http://www.youtube.com/get_video_info?video_id='.$id), $video_data);
$streams = $video_data['url_encoded_fmt_stream_map'];
$streams = explode(',',$streams);
$counter = 1;
foreach ($streams as $streamdata) {
printf("Stream %d:<br/>----------------<br/><br/>", $counter);
parse_str($streamdata,$streamdata);
foreach ($streamdata as $key => $value) {
if ($key == "url") {
$value = urldecode($value);
printf("<strong>%s:</strong> <a href='%s'>video link</a><br/>", $key, $value);
} else {
printf("<strong>%s:</strong> %s<br/>", $key, $value);
}
}
$counter = $counter+1;
printf("<br/><br/>");
}
?>
It's only work with RllJtOw0USI if I change the $id to dMK_npDG12Q it's not working anymore, and I got the errors as follow:
status=fail&errorcode=150&errordetail=0&reason=This+video+contains+content+from+Vevo.+It+is+restricted+from+playback+on+certain+sites+or+applications.%0A%3Ca+href%3D%27http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdMK_npDG12Q%26feature%3Dplayer_embedded%27+target%3D%27_blank%27%3EWatch+on+YouTube%3C%2Fa%3E
How can I get the link from this kind of video?
If you look at reason in json, you can see that
This video contains content from Vevo. It is restricted from playback on certain sites or applications
So you should obey their restrictions, or find any other link which is not restricted yet.
I'm using QRCode from Google API and I put this code in the function.
Now I want to show two images, for example: Two images with different sizes or datas!
It does not matter if you use class or function, I just want to get different output on the page.
This is code:
<?php
function CreateQRCode($data, $size, $logo) {
header('Content-type: image/png');
// Get QR Code image from Google Chart API
// http://code.google.com/apis/chart/infographics/docs/qr_codes.html
$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs='.$size.'&chl='.urlencode($data));
if($logo !== FALSE){
$logo = imagecreatefromstring(file_get_contents($logo));
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
// Scale logo to fit in the QR Code
$logo_qr_width = $QR_width/3;
$scale = $logo_width/$logo_qr_width;
$logo_qr_height = $logo_height/$scale;
imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
}
imagepng($QR);
imagedestroy($QR);
}
CreateQRCode('http://google.com', '200x200', FALSE);
?>
Like this:
example 2
example 1
Hello there i have a php file with the included:
The image shows properly when i access the PHP file, however when I try to show it in the HTML template, it shows as the little img with a crack in it, so basically saying "image not found"
<img src="http://konvictgaming.com/status.php?channel=blindsniper47">
is what i'm using to display it in the HTML template, however it just doesn't seem to want to show, I've tried searching with next to no results for my specific issue, although I'm certain I've probably searched the wrong title
adding code from the OP below
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
echo "<img src='$online' />";
} else {
echo "<img src='$offline' />";
}
The url is not an image, it is a webpage with the following content
<img src='offline.png' alt='Offline' />
Webpages cannot be displayed as images. You will need to edit the page to only transmit the actual image, with the correct http-headers.
You can probably find some help on this by googling for "php dynamic image".
Specify in the HTTP header that it's a PNG (or whatever) image!
(By default they are interpreted as text/html)
in your status.php file, where you output the markup of <img src=... change it to read as follows
$image = file_get_contents("offline.png");
header("Content-Type: image/png");
echo $image;
Which will send an actual image for the request instead of sending markup. markup is not valid src for an img tag.
UPDATE your code modified below.
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
header("Content-Type: image/png");
$image = null;
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
$image = file_get_contents($online);
} else {
$image = file_get_contents($offline);
}
echo $image;
I suppose you change the picture dynmaclly on this page.
Easiest way with least changes will just be using an iframe:
<iframe src="http://konvictgaming.com/status.php?channel=blindsniper47"> </iframe>
In the messages users write with eachother, I wish to turn Youtube links into the youtube thumbnail of it+title.
So how can I check if $msg contains a youtube video link, and if it does, it should take the video id (?v=) of it, and run this:
$.getScript( 'http://gdata.youtube.com/feeds/api/videos/$videoid?v=2&alt=json-in-script&callback=youtubeFetchDataCallback' );
How can this be done?
Already resolved partially here: parse youtube video id using preg_match
EDIT alternatively you could use parse_url() in PHP check the host is youtube and if it is read the query string and split into key/value pairs and read the "v" value
EDIT 2
<?php
$url = "http://www.youtube.com/watch?v=QDe6MZQjpho";
$url = parse_url($url);
if($url['host'] == "www.youtube.com") {
parse_str($url['query'], $output);
$videoID = $output['v'];
} else {
echo "not youtube.com";
}
?>
EDIT 3 Another way
<?php
$url = "http://www.youtube.com/watch?v=QDe6MZQjpho";
if(preg_match("#http://(.*)\.youtube\.com/watch\?v=(.*)(&(.*))?#", $url, $matches)){
$videoID = $matches[2];
} else {
echo "not youtube.com";
}
?>
I'm looking to create a PHP script where, a user will provide a link to a webpage, and it will get the contents of that webpage and based on it's contents, parse the contents.
For example, if a user provides a YouTube link:
http://www.youtube.com/watch?v=xxxxxxxxxxx
Then, it will grab the basic information about that video (thumbnail, embed code?)
Or they might provide a vimeo link:
http://www.vimeo.com/xxxxxx
Or even if they were to provide any link, without a video attached, such as:
http://www.google.com/
And it could grab just the page Title or some meta content.
I'm thinking I'd have to use file_get_contents, but I'm not exactly sure how to use it in this context.
I'm not looking for someone to write the entire code, but perhaps provide me with some tools so that I can accomplish this.
You can use either the curl or the http library. You send a http request, and can use the library to get the information from the http response.
I know this question is quite old, but I'll answer just in case someone hits it looking for the same thing.
Use oEmbed (http://oembed.com/) for YouTube, Vimeo, Wordpress, Slideshare, Hulu, Flickr and many other services. If not in the list or you want to make it more precise, you can use this:
http://simplehtmldom.sourceforge.net/
It's a sort of jQuery for PHP, meaning you can use HTML selectors to get portions of the code (i.e.: all the images, get the contents of a div, return only text (no HTML) contents of a node, etc).
You could do something like this (could be done more elegantly but this is just an example):
require_once("simple_html_dom.php");
function getContent ($item, $contentLength)
{
$raw;
$content = "";
$html;
$images = "";
if (isset ($item->content) && $item->content != "")
{
$raw = $item->content;
$html = str_get_html ($raw);
$content = str_replace("\n", "<BR /><BR />\n\n", trim($html->plaintext));
try
{
foreach($html->find('img') as $image) {
if ($image->width != "1")
{
// Don't include images smaller than 100px height
$include = false;
$height = $image->width;
if ($height != "" && $height >= 100)
{
$include = true;
}
/*else
{
list($width, $height, $type, $attr) = getimagesize($image->src);
if ($height != "" && $height >= 100)
$include = true;
}*/
if ($include == true)
{
$images = $images . '<div class="theImage"><img src="'.$image->src.'" alt="'.$image->alt.'" class="postImage" border="0" /></div>';
}
}
}
}
catch (Exception $e) {
// Do nothing
}
$images = '<div id="images">'.$images.'</div>';
}
else
{
$raw = $item->summary;
$content = str_get_html ($raw)->plaintext;
}
return (substr($content, 0 , $contentLength) . (strlen ($content) > $contentLength ? "..." : "") . $images);
}
file_get_contents() would work in this case assuming that you have allow_fopen_url set to true in your php.ini. What you would do is something like:
$pageContent = #file_get_contents($url);
if ($pageContent) {
preg_match_all('#<embed.*</embed>#', $pageContent, $matches);
$embedStrings = $matches[0];
}
That said, file_get_contents() won't give you much in the way of error handling other receiving the content on success or false on failure. If you would like to have more rich control over the request and access the HTTP response codes, use the curl functions and in particular, curl_get_info, to look at the response codes, mime types, encoding, etc. Once you get the content via either curl or file_get_contents() your code for parsing it to look for the HTML of interest will be the same.
Maybe Thumbshots or Snap already have some of the functionality you want?
I know that's not exactly what you are looking for, but at least for the embedded stuff that might be handy. Also txwikinger already answered your other question. But maybe that helps ypu anyway.