如何从youtube视频制作gif图像?

Anybody help me i want to developing a website using php code. GIF-KING this is my website i have completed jpeg image to gif creator but how to create GIF image from YouTube URL like yt2gif

I tried to search Google but there is not gives any sufficient result to fulfill my requirement.

I got the code upload video to GIF creator but unable to find the script making YouTube URL to GIF creator.

I got one solution first download YouTube video by using YouTube API. then convert it to in GIF images. But that is not the right way. i am unable to convert it in the middle part. Always convert from starting Also it is not possible to download huge number of video from YouTube.

See my process of creating GIF images from YouTube URL.

Screenshot-1 :

Copy the YouTube URL enter image description here

Screenshot-2 :

Paste it in the website http://www.gif-king.com/make-your-gif3 see below screenshot. enter image description here

Click on Create Gifs after some times the video details will appear See screenshot-3.

Screenshot-3 :

Showing the video details from YouTube

After click on Make Gif this video will convert to GIF.

It is working for a small video. but not working it for big video.

My php code:

ajax.php

if(isset($_REQUEST['vid'])){
    $vidID=$_REQUEST['vid'];
    if($vidID){
        include('curl.php');
        include('youtube.php');
        $tube = new youtube();

        $links = $tube->get("http://www.youtube.com/watch?v=".$vidID);
        $getVideo=$links[3]['url']; //Get the avi video from youtube 
        $cate=mysql_query("select * from category ORDER BY id ");
        while($categoryName=mysql_fetch_array($cate)){
            $getCatRes .= '<option value="'.$categoryName['id'].'">'.$categoryName['name'].'</option>';
        }
        if($getVideo) {
            $url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
            $doc = new DOMDocument;
            $doc->load($url);
            $title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
            $duration = $doc->getElementsByTagName('duration')->item(0)->getAttribute('seconds');
            if($duration > 1200){
                $array[] = array('result'=>'error','message'=>'ERROR!!! Maximum 20 minutes video allowed');
            }
            else{
            $newVideo = "gifking_".time().".avi";
            $videoUploaded=file_put_contents("myvideo/".$newVideo,file_get_contents($getVideo));
            if($videoUploaded){
                    $video='<iframe width="360" height="240" frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/'.$vidID.'?enablejsapi=1&amp;playerapiid=ytplayer&amp;version=3&amp;cc_load_policy=0&amp;iv_load_policy=3&amp;modestbranding=1&amp;rel=0&amp;showinfo=0&amp;theme=light"></iframe>';

                    $video_title='<input type="text" class="add-gif-textbox" name="title" id="title" placeholder="Title" value="'.$title.'"  />';
                    $category='<select class="add-gif-dropdown" id="cat_id" name="cat_id">
                                  '.$getCatRes.'
                                  </select>';
                    $tag='<input type="text" class="add-gif-textbox" name="tag" id="tag" placeholder="tiger,book,flower" />';
                    $submitBtn='<input id="button" class="button1" type="submit" value="Make Gif" name="submit">';

                    $array[] = array('result'=>'success','title'=>$video_title,'category'=>$category,'video'=>$video,'duration'=>$duration,'tag'=>$tag,'filename'=>$newVideo,'submit_btn'=>$submitBtn);
                }
                else{
                    $array[] = array('result'=>'error','message'=>'ERROR!!! Uploading image please try again');
                }
            }
        }
        else{
            $array[] = array('result'=>'error','message'=>'ERROR!!! Invalid video id');
        }
        echo json_encode($array);
    }
}

Please suggest me how to creating that in php code?

It works totally easy, lucky for you! Here is a simple step-by-step program of that:

  1. You first of all download the video from Youtube (or any other video website not to make it too specific). This can be done with a download program. Those exist, there are popular ones.

  2. Then you need a video converter program. Those exist, there are popular ones. With it you extract each X frames as an image. Take care to get the timing right so you understand the duration in milliseconds between each of those X frames.

  3. Then you merge all the image files of the extracted frames again with a software that can create an animated gif. Those exist, there are popular ones. Take care here now that you set the timing right between the frames.

  4. Then you save the gif image to a specific filename.

Good News: You are done.

As far as the program of this is concerned (the programming question), you find the steps outlined in the list above.

The implementation depends on tool suggestions which are off-topic here on site (but this shouldn't be show stopper for you as each step above is explained in detail within the interwebs and you seem to be clever enough to use the interwebs otherwise you wouldn't have asked on Stackoverflow).

Good luck and have fun. Let us know how it worked out!

I would suggest using something like ffmpeg(multi platform open source library for converting/recording video) to do most of the more difficult work for you. Take a quick look at this http://www.ffmpeg.org/ and also http://www.catswhocode.com/blog/19-ffmpeg-commands-for-all-needs one of the codes on the second website has one specifically for converting to gif.

You also need to implement the library in PHP, a quick google search reveals many sites that can help you with this. It may involve a plugin or program on the server to allow PHP to automate this process.

I havent done a huge amount of work in PHP but it seems quite possible to convert a youtube video to gif with a bit of work - so i hope this helps.

I thought I would be more specific and expand on my answer as its quite difficult with the character limit in the comments:

As mentioned you will have to follow a few steps. First you must get the video from youtube to convert it: In php you could try a file_get_contents() on the page that refrences the video(or some other download method a simple search for "php download youtube video" reveals many.

Then you will have to convert it to gif. xampp and ffmpeg would be suited to the task though another search of the web with just "convert to gif php" revealed a few options. A found a few tutorials also through that search so it shouldnt be too hard. You should also check out the xampp and ffmpeg websites and see the documentation on them if you choose to go with that.

Once converted you must save the gif with a specific filename, that shouldnt be too hard it also depends on what method youve used to convert it, once again there is plenty of documentation out there to help with this sort of stuff.

So see how it goes and although it would take way too long and be too difficult to show you an example on stackoverflow, if you have a slightly more specific question about one of the steps id be happy to find you a tutorial or try and get a small example working for you. Try your best and im sure with a bit of searching around and effort you'll be able to find out how to do it in no time.

There is a pure PHP solution, but I would advise you to use an external application (via command-line) to make this conversion, simple because PHP is not fast enough to do this kind of video manipulations frequently. The loading times and server load would be awfull.

For the pure PHP solution you could use this class to convert the video file to frames (as, let's say gif images): http://www.phpclasses.org/package/3747-PHP-Manipulate-and-convert-videos-with-ffmpeg-program.html

And then the next solution to convert the images to frames of a .gif image: PHP - Create simple animated GIF from two JPEG images?

For the terminal-based solution, you could take a look at: https://askubuntu.com/questions/107726/how-to-create-animated-gif-images-of-a-screencast

You could also make a connection to a custom application based in another language (let's say; python or C++) and let this program do the hard convertion, while PHP does the rest (maybe creating the GUI?)

If you want to generate gif/image file when you upload file, refer to ffmpeg,

ffmpeg -i orginal.avi -t 10 output.gif

-i: the video file name -t: is the time

if you want to call existed image file with youtube video, click here

I dont think there is something out of the box for your task.
You should develop something to do this.
For example you can:

  1. Download youtube video with this node.js plugin: https://github.com/fent/node-youtube-dl
  2. Convert it with gif.js: http://jnordberg.github.io/gif.js/tests/video.html

Google supply a Youtube API for tasks relating to Youtube videos, image urls included. Youtube-Google Developers

Soluton: 1

I got one solution first download YouTube video by using youtube-to-gif(if this is not installed your server. Please contact with server support team) shell than convert it to in gif images.

Here is my code:

$vodeo_id = 'UiPRwDUGQLE';
$start_second = 5;
$duration = 10;
$filePath = 'some_path_here';
$fileName = 'some_file_name.gif';
exec("youtube-to-gif -u https://www.youtube.com/watch?v={$video_id} -b $start_second -d $duration -s 550x? -o {$filePath}{$fileName} -f 10", $out, $err);

Above is working fine but one problem there. You can't convert to gif from 0 sec. Because youtube-to-gif takes default time from 3 sec to onwards.

Solution: 2

Here is second thought. If you want to convert YouTube to GIF image. You should install following extentions

If above extensions not installed in your server please contact your server support team.

First download YouTube video by using youtube-dl command. Then you easily use ffmpeg command for convert to GIF image.

Here is my code:

$input = 'your video path which you was downloading from YouTube by using youtube-dl commmand';
$start = 5;
$end = 15;
$limit = $end - $start;
$thumbnail = 'img/logo.png'; /* adding watermark on that GIF image */

$storeFolder = 'destination path here';
$targetPath = dirname(__FILE__) . $ds . $storeFolder;
$newName = time() . '.gif';
$destinationPath = $targetPath . $newName;

$command = "ffmpeg -t $limit -ss $start -i $input -i $thumbnail -vf scale=500:-1 -codec:a copy $destinationPath";
@exec($command, $ret, $returnvalue);
if ($returnvalue == 127) {
      $data['message'] = "FFMPEG not installed. Please contact with support team.";
} else {
     $data['message'] = "Success";
}

You can use external API YouTube video to gif Animation.

Sample PHP Code:

$response = Unirest::post(
  "https://squbit-video-to-animation.p.mashape.com/animation",
  array(
    "X-Mashape-Authorization" => "Mashape-Authorization-Key",
    "Content-Type" => "application/json"
  ),
  "{\"sourceId\":\"ZL6a4U_UdTc\",\"width\":\"480\",\"height\":\"270\",\"startTime\":\"192\",\"duration\":\"17\",\"callback\":\"http:\/\/yourhost.com\/callback\/\"}"
);

You specify input parameters in JSON request.

Once your animation is ready you will receive a callback to http://yourhost.com/callback_url/ with a link to created gif animation

Thank you