Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter : Get thumbnail of Youtube video

Tags:

flutter

dart

I am using youtube_player_flutter to play youtube video in my app. Is there any way to get thumbnail of the youtube video in flutter. I have an youtube video URL and I need to get the thumbnail of that url.

Thanks in advance.

like image 524
Siva Perumal Avatar asked Jan 20 '26 00:01

Siva Perumal


2 Answers

Assuming you have a youtube URL of the uploaded video. if you have it then you have to format it like the below URL.

https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg  --  Just add your youtube video Id here

Code Snippet:

Image.network('https://img.youtube.com/vi/6cwnBBAVIwE/0.jpg'),

6cwnBBAVIwE- This is the sample id I added here. You can add yours youtube video id.

You can get the youtube id from the video url, The id is the last 11 digits from the youtube id

For example here the video url is https://www.youtube.com/watch?v=6cwnBBAVIwE

The id for this video is 6cwnBBAVIwE

To get the id :

String url = "https://www.youtube.com/watch?v=H4p6njjPV_o"
String id = url.substring(url.length -11);

OR

if the above solution not working then a more advanced method to resolve it.

1. Get the ID from URL

  String? convertUrlToId(String url, {bool trimWhitespaces = true}) {
  if (!url.contains("http") && (url.length == 11)) return url;
  if (trimWhitespaces) url = url.trim();

  for (var exp in [
    RegExp(
        r"^https:\/\/(?:www\.|m\.)?youtube\.com\/watch\?v=([_\-a-zA-Z0-9]{11}).*$"),
    RegExp(
        r"^https:\/\/(?:www\.|m\.)?youtube(?:-nocookie)?\.com\/embed\/([_\-a-zA-Z0-9]{11}).*$"),
    RegExp(r"^https:\/\/youtu\.be\/([_\-a-zA-Z0-9]{11}).*$")
  ]) {
    Match? match = exp.firstMatch(url);
    if (match != null && match.groupCount >= 1) return match.group(1);
  }

  return null;
}

2. Get the thumbnail URL

String getThumbnail({
  required String videoId,
  String quality = ThumbnailQuality.standard,
  bool webp = true,
}) =>
    webp
        ? 'https://i3.ytimg.com/vi_webp/$videoId/$quality.webp'
        : 'https://i3.ytimg.com/vi/$videoId/$quality.jpg';

Usage:

void main() {
  String? videoId = convertUrlToId(
      "https://www.youtube.com/watch?v=6cwnBBAVIwE");
  String thumbnailUrl = getThumbnail(videoId: videoId ?? "");
  print(thumbnailUrl); 
}

Output:

https://i3.ytimg.com/vi_webp/6cwnBBAVIwE/sddefault.webp

like image 177
Jitesh Mohite Avatar answered Jan 23 '26 20:01

Jitesh Mohite


// File created by
// Lung Razvan <long1eu>
// on 20/01/2021

void main() {
  final String thumbnail = getYoutubeThumbnail('https://www.youtube.com/watch?v=ISPK_eWX3ls');
  print(thumbnail);
}

String getYoutubeThumbnail(String videoUrl) {
  final Uri uri = Uri.tryParse(videoUrl);
  if (uri == null) {
    return null;
  }

  return 'https://img.youtube.com/vi/${uri.queryParameters['v']}/0.jpg';
}

like image 44
Razvan Cristian Lung Avatar answered Jan 23 '26 21:01

Razvan Cristian Lung