Get YouTube or Vimeo Thumbnails in one shot with jQuery

偶尔善良 提交于 2019-12-03 04:07:36
Yi Jiang

You do this by observing that YouTube video thumbnails have a distinct URL pattern, which you can generate by parse out the video id. Vimeo thumbnails can be obtained similarly, but parsing out the video id and then using the simple API to obtain the link to the thumbnail.

I wrote some code to do this for this Meta question; it's not particularly clean but it should work:

function processURL(url, success){
    var id;

    if (url.indexOf('youtube.com') > -1) {
        id = url.split('/')[1].split('v=')[1].split('&')[0];
        return processYouTube(id);
    } else if (url.indexOf('youtu.be') > -1) {
        id = url.split('/')[1];
        return processYouTube(id);
    } else if (url.indexOf('vimeo.com') > -1) {
        if (url.match(/^vimeo.com\/[0-9]+/)) {
            id = url.split('/')[1];
        } else if (url.match(/^vimeo.com\/channels\/[\d\w]+#[0-9]+/)) {
            id = url.split('#')[1];
        } else if (url.match(/vimeo.com\/groups\/[\d\w]+\/videos\/[0-9]+/)) {
            id = url.split('/')[4];
        } else {
            throw new Error('Unsupported Vimeo URL');
        }

        $.ajax({
            url: 'http://vimeo.com/api/v2/video/' + id + '.json',
            dataType: 'jsonp',
            success: function(data) {
                sucess(data[0].thumbnail_large);
            }
        });
    } else {
        throw new Error('Unrecognised URL');
    }

    function processYouTube(id) {
        if (!id) {
            throw new Error('Unsupported YouTube URL');
        }

        sucess('http://i2.ytimg.com/vi/' + id + '/hqdefault.jpg');
    }
}

The function uses a callback because Vimeo API calls are asynchronous.

I used everything that Yi Jiang suggested. I had to change a couple of lines to get it working properly for me, the changes are noted with below:

function processURL(url, success){
var id;

if (url.indexOf('youtube.com') > -1) {
    <!-- CHANGED -->
    id = url.split('v=')[1].split('&')[0];
    return processYouTube(id);
} else if (url.indexOf('youtu.be') > -1) {
    id = url.split('/')[1];
    return processYouTube(id);
} else if (url.indexOf('vimeo.com') > -1) {
    <!-- CHANGED -->
    if (url.match(/http:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/)) {
        id = url.split('/')[1];
    } else if (url.match(/^vimeo.com\/channels\/[\d\w]+#[0-9]+/)) {
        id = url.split('#')[1];
    } else if (url.match(/vimeo.com\/groups\/[\d\w]+\/videos\/[0-9]+/)) {
        id = url.split('/')[4];
    } else {
        throw new Error('Unsupported Vimeo URL');
    }

    $.ajax({
        url: 'http://vimeo.com/api/v2/video/' + id + '.json',
        dataType: 'jsonp',
        success: function(data) {
            <!-- CHANGED -->
             success(data[0].thumbnail_large);
        }
    });
} else {
    throw new Error('Unrecognised URL');
}

function processYouTube(id) {
    if (!id) {
        throw new Error('Unsupported YouTube URL');
    }
    <!-- CHANGED -->
    success('http://i2.ytimg.com/vi/' + id + '/hqdefault.jpg');
}
}

The 2 bottom changes were just to fix the 'success' spelling.

Also, Vimeo uses https://vimeo.com/n format so make the s optional and the id is the 4th[3] not 2nd[1] in the split array:

function get_video_thumb(url, callback){
    var id = get_video_id(url);

    if (id['type'] == 'y') {
        return processYouTube(id);
    } else if (id['type'] == 'v') {

        $.ajax({
            url: 'http://vimeo.com/api/v2/video/' + id['id'] + '.json',
            dataType: 'jsonp',
            success: function(data) {
                callback({type:'v', id:id['id'], url:data[0].thumbnail_large});
            }
        });
    }

    function processYouTube(id) {
        if (!id) {
            throw new Error('Unsupported YouTube URL');
        }

        callback({type:'y',id:id['id'],url:'http://i2.ytimg.com/vi/'+id['id'] + '/hqdefault.jpg'}); 
    }
}

function get_video_id(url) {
        var id;
        var a;
    if (url.indexOf('youtube.com') > -1) {
        id = url.split('v=')[1].split('&')[0];
        return processYouTube(id);
    } else if (url.indexOf('youtu.be') > -1) {
        id = url.split('/')[1];
        return processYouTube(id);
    } else if (url.indexOf('vimeo.com') > -1) {
    if (url.match(/https?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/)) {
        id = url.split('/')[3];
    } else if (url.match(/^vimeo.com\/channels\/[\d\w]+#[0-9]+/)) {
        id = url.split('#')[1];
    } else if (url.match(/vimeo.com\/groups\/[\d\w]+\/videos\/[0-9]+/)) {
        id = url.split('/')[4];
    } else {
        throw new Error('Unsupported Vimeo URL');
    }

    } else {
        throw new Error('Unrecognised URL');
    }
        a = {type:'v',id:id};
        return a;
    function processYouTube(id) {
        if (!id) {
            throw new Error('Unsupported YouTube URL');
        }
                a = {type:'y',id:id};
        return(a); // default.jpg OR hqdefault.jpg
    }
}

I think that now at vimeo.com the id is always the last value...

} else if (sourceVideo.indexOf("vimeo.com") >= 0) {
    id = sourceVideo.split('/');
    id = id[id.length-1];
}

Don't need the 3 regex.

Here is my example,

Sample YouTube URL: https://www.youtube.com/watch?v=DNWo43u6Kqo

Sample Vimeo URL : https://player.vimeo.com/video/30572181

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <title>Video Thumbnails</title>
</head>
<body>
    <div style="width:80%">
        YouTube/Vimeo URL : 
        <input type="text" id="txtVideoLink" value="https://player.vimeo.com/video/30572181" style="width:30%"/>
        <a href="javascript:void(0)" onclick="GetImageFromVideoURL()">Get Video Thumbnail</a>
        <br />
        <br />
        <img src="" id="thumbImg">
    </div>

    <script>
        function GetImageFromVideoURL() {
            var i, image_url, isValidURL, isVValidURL, isEmbValidURL, uniqueIdLength, uniqueID;
            uniqueIdLength = 11;
            image_url = $('#txtVideoLink').val();

            var url;
            if (image_url != null) {
                url = image_url;
            }
            else {
                url = "";
            }

            if (url.search("youtube") != -1) {
                isValidURL = image_url.indexOf("www.youtube.com/watch?v=");
                isVValidURL = image_url.indexOf("www.youtube.com/v/");
                isEmbValidURL = image_url.indexOf("www.youtube.com/embed/");

                if (isValidURL == -1 && isVValidURL == -1 && isEmbValidURL == -1) {
                    alert("Invalid URL");
                    return false;
                }

                if (isValidURL != -1) {
                    i = image_url.indexOf("v=");
                }
                else if (isVValidURL != -1) {
                    i = image_url.indexOf("v/");
                }
                else if (isEmbValidURL != -1) {
                    i = image_url.indexOf("embed/");
                    i = i + 4;
                }
                i = i + 2;

                uniqueID = image_url.substr(i, uniqueIdLength);
                imageURL = 'https://img.youtube.com/vi/' + uniqueID + '/0.jpg';
                $('#thumbImg').attr("src", imageURL);
                return true;
            }
            else if ((url.search("vimeo") != -1)) {
                isVimeoURL = image_url.indexOf("vimeo.com/video");
                isvVimeoURL = image_url.indexOf("www.vimeo.com/video");
                if (isVimeoURL == -1 && isvVimeoURL == -1) {
                    alert("Invalid URL");
                    return false;
                }

                if (isVimeoURL != -1) {
                    i = image_url.indexOf("video/");
                }
                i = i + 6;

                uniqueID = image_url.substr(i, uniqueIdLength);

                $.ajax({
                    type: 'GET',
                    url: 'https://vimeo.com/api/v2/video/' + uniqueID + '.json',
                    jsonp: 'callback',
                    dataType: 'jsonp',
                    success: function (data) {
                        var thumbnail_src = data[0].thumbnail_large;
                        $('#thumbImg').attr("src", thumbnail_src);
                    }
                });
                return true;
            }
            alert("Invalid URL");
            $('#txtVideoLink').val("");
            return false;
        }

    </script>
</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!