Domanda

Se dispongo dell'URL di un video di YouTube, esiste un modo per utilizzare PHP e cURL per ottenere la miniatura associata dall'API di YouTube?

È stato utile?

Soluzione

Ogni video YouTube ha quattro immagini generate. Essi sono prevedibilmente formattati come segue:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg

Il primo della lista è un'immagine full size e altri sono immagini in miniatura. L'immagine in miniatura di default (cioè, uno dei 1.jpg, 2.jpg, 3.jpg) è:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

Per la versione ad alta qualità della miniatura utilizzare un URL simile a questo:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

C'è anche una versione media qualità della miniatura, utilizzando un URL simile al HQ:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

Per la versione a definizione standard della miniatura, utilizzare un URL simile a questo:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

Per la versione massima risoluzione della miniatura utilizzare un URL simile a questo:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

Tutti gli URL di cui sopra sono disponibili su HTTP troppo. Inoltre, il nome host i3.ytimg.com leggermente più corta lavora al posto di img.youtube.com negli URL di esempio di cui sopra.

In alternativa, è possibile utilizzare il YouTube Data API (v3) per ottenere immagini in miniatura.

Altri suggerimenti

È possibile utilizzare YouTube Data API per recuperare miniature video , titolo, descrizione, valutazione, statistiche e altro ancora. API versione 3 richiede una chiave *. Ottenere la chiave e creare un Video: list richiesta:

https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=VIDEO_ID

Esempio Codice PHP

$data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=T0Jqdjbed40");
$json = json_decode($data);
var_dump($json->items[0]->snippet->thumbnails);

Output

object(stdClass)#5 (5) {
  ["default"]=>
  object(stdClass)#6 (3) {
    ["url"]=>
    string(46) "https://i.ytimg.com/vi/T0Jqdjbed40/default.jpg"
    ["width"]=>
    int(120)
    ["height"]=>
    int(90)
  }
  ["medium"]=>
  object(stdClass)#7 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/mqdefault.jpg"
    ["width"]=>
    int(320)
    ["height"]=>
    int(180)
  }
  ["high"]=>
  object(stdClass)#8 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/hqdefault.jpg"
    ["width"]=>
    int(480)
    ["height"]=>
    int(360)
  }
  ["standard"]=>
  object(stdClass)#9 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/sddefault.jpg"
    ["width"]=>
    int(640)
    ["height"]=>
    int(480)
  }
  ["maxres"]=>
  object(stdClass)#10 (3) {
    ["url"]=>
    string(52) "https://i.ytimg.com/vi/T0Jqdjbed40/maxresdefault.jpg"
    ["width"]=>
    int(1280)
    ["height"]=>
    int(720)
  }
}

* Non solo avete bisogno di un tasto, il sistema può richiedere per informazioni sulla fatturazione in base al numero di richieste API che si intende fare. Tuttavia, alcuni milioni di richieste al giorno sono liberi.

Fonte articolo .

Che Asaf ha detto è giusto. Tuttavia, non tutti i video di YouTube contiene tutti nove miniature. Inoltre, le dimensioni delle immagini delle miniature dipende dal video (i numeri che seguono si basano su uno).

Ci sono sette thumbnails garantiti di esistere:

| Thumbnail Name      | Size (px) | URL                                              |
|---------------------|-----------|--------------------------------------------------|
| Player Background   | 480x360   | https://i1.ytimg.com/vi/<VIDEO ID>/0.jpg         |
| Start               | 120x90    | https://i1.ytimg.com/vi/<VIDEO ID>/1.jpg         |
| Middle              | 120x90    | https://i1.ytimg.com/vi/<VIDEO ID>/2.jpg         |
| End                 | 120x90    | https://i1.ytimg.com/vi/<VIDEO ID>/3.jpg         |
| High Quality        | 480x360   | https://i1.ytimg.com/vi/<VIDEO ID>/hqdefault.jpg |
| Medium Quality      | 320x180   | https://i1.ytimg.com/vi/<VIDEO ID>/mqdefault.jpg |
| Normal Quality      | 120x90    | https://i1.ytimg.com/vi/<VIDEO ID>/default.jpg   |

In aggiunta, possono o non possono esistere gli altri due miniature. La loro presenza è probabilmente basato sul fatto che il video è di alta qualità.

| Thumbnail Name      | Size (px) | URL                                                  |
|---------------------|-----------|------------------------------------------------------|
| Standard Definition | 640x480   | https://i1.ytimg.com/vi/<VIDEO ID>/sddefault.jpg     |
| Maximum Resolution  | 1920x1080 | https://i1.ytimg.com/vi/<VIDEO ID>/maxresdefault.jpg |

Si possono trovare script JavaScript e PHP per recuperare le miniature e altri Informazioni su YouTube in:

È inoltre possibile utilizzare il strumento YouTube Video Informazioni Generator per ottenere tutte le informazioni su un video di YouTube presentando un URL o un video id.

In YouTube API V3 possiamo anche usare questi URL per ottenere le miniature ... sono classificati in base alla loro qualità.

https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/default.jpg -   default
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg - medium 
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg - high
https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/sddefault.jpg - standard

E per la risoluzione massima ..

https://i1.ytimg.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

Un vantaggio di questi URL oltre gli URL nella prima risposta è che questi URL non vengano bloccati da firewall.

Se si desidera che la più grande immagine da YouTube per uno specifico ID video, quindi l'URL deve essere qualcosa di simile:

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

Utilizzando l'API, è possibile ritirare immagine predefinita miniatura. semplice codice dovrebbe essere qualcosa di simile:

//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);

Se si vuole sbarazzarsi delle "barre nere" e farlo come YouTube fa, è possibile utilizzare:

https://i.ytimg.com/vi_webp/<video id>/mqdefault.webp

E se non è possibile utilizzare l'estensione del file .webp si può fare in questo modo:

https://i.ytimg.com/vi/<video id>/mqdefault.jpg

Inoltre, se avete bisogno della versione non in scala, utilizzare maxresdefault invece di mqdefault.

Nota: Non sono sicuro circa il rapporto di aspetto, se hai intenzione di usare maxresdefault

.

Ho fatto una funzione per andare a prendere solo le immagini già esistenti da YouTube

function youtube_image($id) {
    $resolution = array (
        'maxresdefault',
        'sddefault',
        'mqdefault',
        'hqdefault',
        'default'
    );

    for ($x = 0; $x < sizeof($resolution); $x++) {
        $url = '//img.youtube.com/vi/' . $id . '/' . $resolution[$x] . '.jpg';
        if (get_headers($url)[0] == 'HTTP/1.0 200 OK') {
            break;
        }
    }
    return $url;
}

YouTube Data API v3 , è possibile ottenere le miniature del video con la Video-> funzione lista . Da snippet.thumbnails (chiave). , è possibile scegliere la miniatura di default, media o alta risoluzione, e ottenere la sua larghezza, l'altezza e l'URL.

È inoltre possibile aggiornare le miniature con la thumbnails-> set funzionalità .

Per esempi, è possibile controllare la YouTube I campioni API progetto. ( quelli PHP .)

È possibile ottenere il videocitofono che contiene l'URL alla miniatura del video. Non c'è esempio di codice nel link. Oppure, se si vuole analizzare XML, ci sono informazioni qui . L'XML restituito ha un elemento media:thumbnail, che contiene l'URL della miniatura.

// 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 è di proprietà di Google e Google ama avere un numero ragionevole di immagini per le diverse dimensioni dello schermo, quindi le sue immagini sono memorizzate in diverse dimensioni. Ecco un esempio di come la miniatura sarà come:

miniature Bassa qualità:

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

miniature Media Qualità:

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

L'alta qualità delle miniature:

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

miniature massima qualità:

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

YouTube versione API 3 installato e funzionante in 2 minuti

Se tutto quello che vogliamo fare è cercare su YouTube e ottenere le proprietà associate:

  1. Prendi un API pubblica - Questo collegamento dà una buona direzione

  2. Utilizzare sotto stringa di query. La query di ricerca (indicato con q = ) nella stringa URL è StackOverflow a scopo di esempio. YouTube ti invierà indietro una risposta JSON in cui è possibile quindi analizzare per Thumbnail, Snippet, autore, ecc.

    https: //www.googleapis .com / youtube / v3 / search? part = id% 2Csnippet & maxResults = 50 & q = StackOverflow & key = YOUR_API_KEY_HERE

Usa:

https://www.googleapis.com/youtube/v3/videoCategories?part=snippet,id&maxResults=100&regionCode=us&key=**Your YouTube ID**

Sopra è il link. Usando questo, si possono trovare le caratteristiche di YouTube di video. Dopo aver trovato le caratteristiche, è possibile ottenere i video della categoria selezionata. Dopo di allora si può trovare selezionato le immagini video utilizzando la risposta di Asaf .

Prova il metodo di cui sopra e si può analizzare tutto dal API .

Ho usato le miniature di YouTube in questo modo:

$url = 'http://img.youtube.com/vi/' . $youtubeId . '/0.jpg';
$img = dirname(__FILE__) . '/youtubeThumbnail_'  . $youtubeId . '.jpg';
file_put_contents($img, file_get_contents($url));

Ricordati YouTube impedisce di inserire le immagini direttamente dal proprio server.

Ho trovato questo ingegnoso strumento che ti permette di creare l'immagine con il tasto PLAY YouTube posta sopra l'immagine:

Giusto per aggiungere / espandere le soluzioni presentate, sento che è necessario notare che, come ho avuto questo problema io stesso, si può effettivamente afferrare più contenuti video di YouTube, in questo caso, le miniature, con richiesta di un HTTP:

Utilizzando un client di riposo, in questo caso, HTTPFUL, si può fare qualcosa di simile:

<?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);

?>

Un'altra alternativa sarebbe quella di utilizzare il oEmbed API che è supportato da YouTube.

È sufficiente aggiungere l'URL di YouTube al oEmbed URL e riceverai un JSON tra cui una miniatura e il codice HTML per l'incorporamento.

Esempio:

http://www.youtube.com/oembed?format=json&url=http%3A//youtube.com/watch%3Fv%3DDLzxrzFCyOs

darebbe:

{
  thumbnail_url: "https://i.ytimg.com/vi/DLzxrzFCyOs/hqdefault.jpg",
  width: 459,
  author_name: "AllKindsOfStuff",
  version: "1.0",
  author_url: "https://www.youtube.com/channel/UCLNd5EtH77IyN1frExzwPRQ",
  thumbnail_width: 480,
  type: "video",
  provider_url: "https://www.youtube.com/",
  html: "<iframe width="459" height="344" src="https://www.youtube.com/embed/DLzxrzFCyOs?feature=oembed" frameborder="0" allowfullscreen></iframe>",
  title: "Some title bla bla foo bar",
  thumbnail_height: 360,
  provider_name: "YouTube",
  height: 344
}

Leggi la documentazione per ulteriori informazioni .

Una semplice funzione PHP che ho creato per la miniatura di YouTube e le tipologie sono

  • default
  • hqdefault
  • mqdefault
  • sddefault
  • maxresdefault

function get_youtube_thumb($link,$type){

    $video_id = explode("?v=", $link);

    if (empty($video_id[1])){
        $video_id = explode("/v/", $link);
        $video_id = explode("&", $video_id[1]);
        $video_id = $video_id[0];
    }
    $thumb_link = "";

    if($type == 'default'   || $type == 'hqdefault' ||
       $type == 'mqdefault' || $type == 'sddefault' ||
       $type == 'maxresdefault'){

        $thumb_link = 'http://img.youtube.com/vi/'.$video_id.'/'.$type.'.jpg';

    }elseif($type == "id"){
        $thumb_link = $video_id;
    }
    return $thumb_link;}

Se si utilizza l'API pubblica, il modo migliore per farlo sta usando dichiarazioni if.

Se il video è pubblica o privata, è possibile impostare la miniatura utilizzando il metodo URL. Se il video è privato si utilizza l'API per ottenere la miniatura.

<?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';
    }

YouTube Data API

YouTube ci fornisce le quattro immagini generate per ogni video tramite l'API dei dati (v3), per esempio,

  1. https://i.ytimg.com/vi/V_zwalcR8DU/ maxresdefault.jpg

  2. https://i.ytimg.com/vi/V_zwalcR8DU/ sddefault.jpg

  3. https://i.ytimg.com/vi/V_zwalcR8DU/ hqdefault.jpg

  4. https://i.ytimg.com/vi/V_zwalcR8DU/ mqdefault.jpg

Come l'accesso alle immagini tramite l'API

  1. In primo luogo ottenere la vostra chiave API pubblica a Google API Console .
  2. Come da riferimento miniatura di YouTube nel API documentazione , è necessario accedere alle risorse su snippet.thumbnails.
  3. Come per questo, è necessario formulare la propria URL come questo -

    www.googleapis.com/youtube/v3/videos?part=snippet&id=`yourVideoId`&key=`yourApiKey`
    

Ora modificare l'ID video e la tua chiave API per il vostro rispettivo di video-id e API-chiave e la sua risposta sarà un uscita JSON fornire i quattro collegamenti nelle miniature delle variabili frammento (se tutti sono disponibili).

È possibile ottenere l'ID video dal video url di YouTube utilizzando parse_url , parse_str e quindi inserire nel agli URL predittivi per le immagini . Grazie a YouTube per gli URL di previsione

$videoUrl = "https://www.youtube.com/watch?v=8zy7wGbQgfw";
parse_str( parse_url( $videoUrl, PHP_URL_QUERY ), $my_array_of_vars );
$ytID = $my_array_of_vars['v']; //gets video ID

print "https://img.youtube.com/vi/<?php print $ytID?>/maxresdefault.jpg";
print "https://img.youtube.com/vi/<?php print $ytID?>/mqdefault.jpg";
print "https://img.youtube.com/vi/<?php print $ytID?>/hqdefault.jpg";
print "https://img.youtube.com/vi/<?php print $ytID?>/sddefault.jpg";
print "https://img.youtube.com/vi/<?php print $ytID?>/default.jpg";

È possibile utilizzare questo strumento per generare le miniature di YouTube

https://tools.tutsplanet.com/index.php / get-youtube-video-miniature

Credo che loro sono un sacco di risposta per miniature, ma voglio aggiungere alcuni altri URL per ottenere YouTube miniature molto facilmente. Sto solo prendendo un testo dalla risposta di Asaf. Qui ci sono alcuni URL per ottenere le miniature di YouTube:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/default.jpg

Per la versione ad alta qualità della miniatura utilizzare un URL simile a questo:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

C'è anche una versione media qualità della miniatura, utilizzando un URL simile a quello di alta qualità:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

Per la versione a definizione standard della miniatura, utilizzare un URL simile a questo:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

Per la versione massima risoluzione della miniatura utilizzare un URL simile a questo:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
    function get_video_thumbnail( $src ) {
            $url_pieces = explode('/', $src);
            if( $url_pieces[2] == 'dai.ly'){
                $id = $url_pieces[3];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if($url_pieces[2] == 'www.dailymotion.com'){
                $id = $url_pieces[4];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if ( $url_pieces[2] == 'vimeo.com' ) { // If Vimeo
                $id = $url_pieces[3];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'youtu.be' ) { // If Youtube
                $extract_id = explode('?', $url_pieces[3]);
                $id = $extract_id[0];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            }else if ( $url_pieces[2] == 'player.vimeo.com' ) { // If Vimeo
                $id = $url_pieces[4];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'www.youtube.com' ) { // If Youtube
                $extract_id = explode('=', $url_pieces[3]);
                $id = $extract_id[1];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            } else{
                $thumbnail = tim_thumb_default_image('video-icon.png', null, 147, 252);
            }
            return $thumbnail;
        }

get_video_thumbnail('https://vimeo.com/154618727');
get_video_thumbnail('https://www.youtube.com/watch?v=SwU0I7_5Cmc');
get_video_thumbnail('https://youtu.be/pbzIfnekjtM');
get_video_thumbnail('http://www.dailymotion.com/video/x5thjyz');

Il top risposta è ottimizzato per l'uso manuale. L'ID del token video senza separatori permette di selezionare con un doppio clic.

Ogni video YouTube ha quattro immagini generate. Essi sono prevedibilmente formattati come segue:

https://img.youtube.com/vi/YOUTUBEVIDEOID/0.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/1.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/2.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/3.jpg

Il primo della lista è un'immagine full size e altri sono immagini in miniatura. L'immagine predefinita miniatura (. Vale a dire uno dei 1.jpg, 2.jpg, 3.jpg) è:

https://img.youtube.com/vi/YOUTUBEVIDEOID/default.jpg

Per la versione ad alta qualità della miniatura utilizzare un URL simile a questo:

https://img.youtube.com/vi/YOUTUBEVIDEOID/hqdefault.jpg

C'è anche una versione media qualità della miniatura, utilizzando un URL simile al HQ:

https://img.youtube.com/vi/YOUTUBEVIDEOID/mqdefault.jpg

Per la versione a definizione standard della miniatura, utilizzare un URL simile a questo:

https://img.youtube.com/vi/YOUTUBEVIDEOID/sddefault.jpg

Per la versione massima risoluzione della miniatura utilizzare un URL simile a questo:

https://img.youtube.com/vi/YOUTUBEVIDEOID/maxresdefault.jpg

Tutti gli URL di cui sopra sono disponibili su HTTP troppo. Inoltre, il nome host i3.ytimg.com leggermente più corta lavora al posto di img.youtube.com negli URL di esempio di cui sopra.

In alternativa, è possibile utilizzare il YouTube dati (v3) per ottenere immagini in miniatura .

Metodo 1:

Puoi trovare tutte le informazioni per un video di YouTube con una pagina JSON che abbia anche "thumbnail_url",http://www.youtube.com/oembed?format=json&url={l'URL del tuo video va qui}

Come l'aspetto dell'URL finale + codice di test PHP

$data = file_get_contents("https://www.youtube.com/oembed?format=json&url=https://www.youtube.com/watch?v=_7s-6V_0nwA");
$json = json_decode($data);
var_dump($json);

Produzione

object(stdClass)[1]
  public 'width' => int 480
  public 'version' => string '1.0' (length=3)
  public 'thumbnail_width' => int 480
  public 'title' => string 'how to reminder in window as display message' (length=44)
  public 'provider_url' => string 'https://www.youtube.com/' (length=24)
  public 'thumbnail_url' => string 'https://i.ytimg.com/vi/_7s-6V_0nwA/hqdefault.jpg' (length=48)
  public 'author_name' => string 'H2 ZONE' (length=7)
  public 'type' => string 'video' (length=5)
  public 'author_url' => string 'https://www.youtube.com/channel/UC9M35YwDs8_PCWXd3qkiNzg' (length=56)
  public 'provider_name' => string 'YouTube' (length=7)
  public 'height' => int 270
  public 'html' => string '<iframe width="480" height="270" src="https://www.youtube.com/embed/_7s-6V_0nwA?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>' (length=171)
  public 'thumbnail_height' => int 360

Per i dettagli, puoi anche vedere https://www.youtube.com/watch?v=mXde7q59BI8 videotutorial 1

Metodo 2:

Utilizzando il collegamento immagine di YouTube,https://img.youtube.com/vi/"inserisci-id-video-youtube-qui"/default.jpg

Metodo 3:

Utilizzando il codice sorgente del browser per ottenere la miniatura utilizzando il link URL video -Go al codice sorgente video e cerca ThumbNailuRL.Ora puoi usare questo URL nel tuo codice sorgente:

{img src="https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg"}

Per i dettagli puoi anche vedere Come ottenere una miniatura del video di YouTube utilizzando l'IDOhttps://www.youtube.com/watch?v=9f6E8MeM6PIvideotutorial 2

Usa img.youtube.com/vi/YouTubeID/ImageFormat.jpg

Ecco i formati di immagine sono diversi come impostazione predefinita, hqdefault, maxresdefault.

Questo è il mio lato client-only no-API-chiave necessaria soluzione.

YouTube.parse('https://www.youtube.com/watch?v=P3DGwyl0mJQ').then(_ => console.log(_))

Il codice:

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`

Utility 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
    })
}

Utility 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
    },
    {})
}

Ecco una semplice funzione che ho creato per ottenere le miniature. E 'facile da capire e da usare.

$ link è il link di YouTube copiato esattamente come lo è nel browser, ad esempio, https :? //www.youtube.com/watch v = BQ0mxQXmLsk

function get_youtube_thumb($link){
    $new = str_replace('https://www.youtube.com/watch?v=', '', $link);
    $thumbnail = 'https://img.youtube.com/vi/' . $new . '/0.jpg';
    return $thumbnail;
}

Salvate questo codice in un file .php vuota e testarlo.

<img src="<?php echo youtube_img_src('9bZkp7q19f0', 'high');?>" />
<?php
// Get a YOUTUBE video thumb image's source url for IMG tag "src" attribute:
// $ID = YouYube video ID (string)
// $size = string (default, medium, high or standard)
function youtube_img_src ($ID = null, $size = 'default') {
    switch ($size) {
        case 'medium':
            $size = 'mqdefault';
            break;
        case 'high':
            $size = 'hqdefault';
            break;
        case 'standard':
            $size = 'sddefault';
            break;
        default:
            $size = 'default';
            break;
    }
    if ($ID) {
        return sprintf('https://img.youtube.com/vi/%s/%s.jpg', $ID, $size);
    }
    return 'https://img.youtube.com/vi/ERROR/1.jpg';
}

Grazie.

public const string tubeThumb = "http://i.ytimg.com/vi/[id]/hqdefault.jpg";
vid.Thumbnail = tubeThumb.Replace("[id]", vid.VideoID);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top