Pregunta

Si tengo la URL de un vídeo de YouTube, ¿hay alguna forma de utilizar PHP y cURL para obtener la miniatura asociada desde la API de YouTube?

¿Fue útil?

Solución

Cada vídeo de YouTube tiene cuatro imágenes generadas. Se previsiblemente el formato siguiente:

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

La primera en la lista es una imagen de tamaño completo y otros son imágenes en miniatura. La imagen miniatura predeterminada (es decir, uno de 1.jpg, 2.jpg, 3.jpg) es:

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

Para la versión de alta calidad de la miniatura usar una URL similar a la siguiente:

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

También hay una versión mediana calidad de la imagen, usando una URL similar a la HQ:

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

Para la versión de definición estándar de la miniatura, utilice una URL similar a la siguiente:

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

Para la versión máxima resolución de la miniatura usar una URL similar a la siguiente:

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

Todas las URL anteriores están disponibles a través de HTTP también. Además, el ligeramente más corto i3.ytimg.com nombre de host funciona en lugar de img.youtube.com En el ejemplo URL anteriores.

Como alternativa, se puede utilizar el API de datos de YouTube (v3) para obtener imágenes en miniatura.

Otros consejos

Puedes usar API de datos de YouTube para recuperar miniaturas de videos, subtítulos, descripción, calificación, estadísticas y más.La versión 3 de API requiere una clave*.Obtenga la clave y cree una vídeos:lista pedido:

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

Ejemplo de código 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);

Producción

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

* No solo necesita una clave, es posible que se le solicite información de facturación según la cantidad de solicitudes de API que planee realizar.Sin embargo, unos pocos millones de solicitudes por día son gratuitas.

Artículo fuente.

¿Qué Asaf dijo que es correcto. Sin embargo, no todos los vídeos de YouTube contiene los nueve miniaturas. Además, los tamaños de las imágenes miniaturas depende de la de vídeo (los números a continuación se basan en uno).

Hay siete miniaturas garantizados de existir:

| 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   |

Además, pueden o no pueden existir los otros dos miniaturas. Su presencia se basa probablemente en si el vídeo es de alta calidad.

| 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 |

Puede encontrar scripts de JavaScript y PHP para recuperar imágenes en miniatura y otros información en YouTube:

También puede utilizar la herramienta YouTube Video Información Generador para obtener toda la información acerca de un vídeo de YouTube mediante la presentación de una URL o el ID de vídeo.

En YouTube V3 API también podemos utilizar estas URL para la obtención de imágenes en miniatura ... Se clasifican en función de su calidad.

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

Y para la resolución máxima ..

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

Una de las ventajas de estas direcciones URL más de las direcciones URL en la primera respuesta es que estas URL no sean bloqueados por los cortafuegos.

Si desea que la imagen más grande de YouTube para un ID de vídeo específico, entonces el URL debe ser algo como esto:

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

El uso de la API, se puede recoger la imagen miniatura predeterminada. simple código debe ser algo como esto:

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

Si desea deshacerse de las "barras negras" y lo hace como YouTube lo hace, puede utilizar:

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

Y si no se puede utilizar la extensión de archivo .webp puede hacerlo de esta manera:

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

Además, si usted necesita la versión sin escala, en lugar de utilizar maxresdefault mqdefault.

Nota: No estoy seguro acerca de la relación de aspecto si usted está planeando utilizar maxresdefault

.

Hice una función única a buscar imágenes existentes de 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;
}

API de datos de YouTube v3 , puede obtener las miniaturas de vídeo con el videos-> función de lista . De snippet.thumbnails. (Llave) , usted puede escoger el valor por defecto, media o alta resolución miniatura, y obtener su anchura, la altura y la dirección URL.

También puede actualizar miniaturas con la thumbnails-> set funcionalidad .

Para ejemplos, se puede extraer la YouTube Las muestras de API proyecto. ( los PHP .)

Usted puede obtener el entrada de vídeo que contiene la dirección URL a la miniatura del vídeo. No hay código de ejemplo en el enlace. O, si se quiere analizar XML, no hay información aquí . El XML devuelto tiene un elemento media:thumbnail, que contiene la dirección URL de la imagen en 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 es propiedad de Google y Google le gusta tener un número razonable de imágenes para diferentes tamaños de pantalla, por lo tanto, sus imágenes se almacenan en diferentes tamaños. Aquí está un ejemplo de cómo la uña del pulgar será como:

miniatura de baja calidad:

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

Miniatura mediana calidad:

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

miniatura de alta calidad:

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

miniatura máxima calidad:

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

YouTube versión API 3 en funcionamiento en 2 minutos

Si todo lo que quiero hacer es buscar YouTube y obtener propiedades asociadas:

  1. Obtener una API pública - Este enlace da una buena dirección

  2. Utilice a continuación la cadena de consulta. La consulta de búsqueda (denotado por q = ) en la cadena de URL es stackoverflow con fines de ejemplo. YouTube le enviará de vuelta una respuesta JSON, donde luego se puede analizar de miniatura, de fragmentos, Autor, etc.

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

Uso:

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

Por encima está el enlace. Usando esto, se pueden encontrar las características de YouTube de vídeos. Después de encontrar características, puede obtener vídeos de la categoría seleccionada. Después de entonces usted puede encontrar imágenes de vídeo seleccionada utilizando la respuesta de Asaf .

Trate el enfoque anterior y se puede analizar todo, desde la API .

He utilizado miniaturas de YouTube de esta manera:

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

Recuerde YouTube impide incluir imágenes directamente desde su servidor.

He encontrado esta ingeniosa herramienta que le permite crear la imagen con el botón de reproducción de YouTube colocado sobre la imagen:

Sólo para añadir / ampliar las soluciones dadas, siento que es necesario tener en cuenta que, como ya he tenido este problema por mí mismo, uno puede realmente tomar múltiples contenido de los vídeos de YouTube, en este caso, las miniaturas, con la petición de un HTTP:

El uso de un resto de cliente, en este caso, HTTPFUL, se puede hacer algo como esto:

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

?>

Otra buena alternativa sería utilizar el oEmbed API que es apoyado por YouTube.

Sólo tiene que añadir su URL de YouTube a la URL oEmbed y recibirá un JSON que incluye una imagen en miniatura y el código HTML para incrustar.

Ejemplo:

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

¿Quieres que dar:

{
  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
}

Lea la documentación para obtener más información .

Una función de PHP sencilla que he creado para la miniatura de YouTube y los tipos son

  • por defecto
  • 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;}

Si está utilizando la API pública, la mejor manera de hacerlo es usando declaraciones if.

Si el vídeo es público o restringido, se establece la miniatura usando el método de URL. Si el vídeo es privado utiliza la API para obtener 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';
    }

API de datos de YouTube

YouTube nos ofrece las cuatro imágenes generadas por cada video a través de la API de datos (v3), por ejemplo,

  1. https://i.ytimg.com/vi/V_zwalcR8DU/ la respuesta correcta en

  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

para acceder a las imágenes a través de la API

  1. En primer lugar obtener su clave API pública en Google API de consola .
  2. Según referencia de la miniatura de YouTube en el API documentación , es necesario acceder a los recursos en snippet.thumbnails.
  3. De acuerdo con esto, es necesario plantear la URL como esto -

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

Ahora cambiar el ID de vídeo y su clave de API a la de su respectivo vídeo-id y clave de API y su respuesta será una salida de JSON que le proporciona los cuatro eslabones de las miniaturas de las variables fragmento (si todos están disponibles).

Puede obtener el ID de vídeo de la URL del video de YouTube usando parse_url , parse_str y luego insertar a las URL de predicción de imágenes . Gracias a YouTube para las direcciones URL predictivos

$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";

Puede utilizar esta herramienta para generar miniaturas de YouTube

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

Creo que su son un montón de respuesta para miniatura, pero quiero añadir algunas otras direcciones URL de YouTube para obtener miniatura con mucha facilidad. Sólo estoy tomando un poco de texto de la respuesta de Asaf. Aquí hay algunas direcciones URL para obtener imágenes en miniatura de YouTube:

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

Para la versión de alta calidad de la miniatura usar una URL similar a la siguiente:

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

También hay una versión mediana calidad de la imagen, usando una URL similar a la alta calidad:

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

Para la versión de definición estándar de la miniatura, utilice una URL similar a la siguiente:

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

Para la versión máxima resolución de la miniatura usar una URL similar a la siguiente:

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

La respuesta superior está optimizado para su uso manual. El token de ID de vídeo sin separadores permite seleccionar con un doble clic.

Cada vídeo de YouTube tiene cuatro imágenes generadas. Se previsiblemente el formato siguiente:

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

La primera en la lista es una imagen de tamaño completo y otros son imágenes en miniatura. La imagen miniatura predeterminada (. Es decir, uno de 1.jpg, 2.jpg, 3.jpg) es:

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

Para la versión de alta calidad de la miniatura usar una URL similar a la siguiente:

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

También hay una versión mediana calidad de la imagen, usando una URL similar a la HQ:

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

Para la versión de definición estándar de la miniatura, utilice una URL similar a la siguiente:

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

Para la versión máxima resolución de la miniatura usar una URL similar a la siguiente:

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

Todas las URL anteriores están disponibles a través de HTTP también. Además, el ligeramente más corto i3.ytimg.com nombre de host funciona en lugar de img.youtube.com En el ejemplo URL anteriores.

Como alternativa, puede utilizar la API de href="https://developers.google.com/youtube/v3/" rel="nofollow de datos de YouTube (v3) para obtener imágenes en miniatura .

Método 1:

Puede encontrar toda la información de un vídeo de YouTube con una página JSON que tiene incluso "thumbnail_url", http://www.youtube.com/oembed?format=json&url= { su URL de vídeo va aquí}

Como aspecto código de prueba final URL + 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);

salida

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

Para más detalles, se puede ver también https://www.youtube.com/watch? v = mXde7q59BI8 video tutorial 1

Método 2:

El uso de YouTube Enlace de imagen, https://img.youtube.com/vi/ "insert-youtube-video-ID- aquí "/default.jpg

Método 3:

El uso de código fuente del navegador para obtener miniatura utilizando el enlace URL de vídeo -ir al código fuente de vídeo y la búsqueda de thumbnailUrl. Ahora puede utilizar esta URL en su código fuente:

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

Para más información también se puede ver Como llegar una miniatura de vídeo de YouTube utilizando Identificación o https://www.youtube.com/watch?v=9f6E8MeM6PI video tutorial 2

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

Aquí formatos de imagen son diferentes, como por defecto, hqdefault, maxresdefault.

Esta es mi cliente de lado solamente no-API-key-requerido solución.

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

El código:

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 Utilidad:

// 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 Utilidad:

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

Esta es una función simple que creé para conseguir las miniaturas. Es fácil de entender y utilizar.

$ enlace es el enlace de YouTube copiado tal y como es en el navegador, por ejemplo, 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;
}

Guardar este código en el archivo .php vacío y probarlo.

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

Gracias.

public const string tubeThumb = "http://i.ytimg.com/vi/[id]/hqdefault.jpg";
vid.Thumbnail = tubeThumb.Replace("[id]", vid.VideoID);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top