7

Is it possible to convert recorded video into GIF in Android programmatically? Can you help me with some sniped code or tell me how to do it?

Naskov
  • 4,121
  • 5
  • 38
  • 62

2 Answers2

12

My advice would be to use MediaMetadataRetriever and call getFrameAtTime() method to retrieve the frames you want to extract:

// Get your video file
File myVideo = new File
         (Environment.getExternalStorageDirectory().getAbsolutePath(),
                                                               "YOUR_FILE.mp4");
// URI to your video file
Uri myVideoUri = Uri.parse(myVideo.toString());

// MediaMetadataRetriever instance
MediaMetadataRetriever mmRetriever = new MediaMetadataRetriever();
mmRetriever.setDataSource(myVideo.getAbsolutePath());

// Array list to hold your frames
ArrayList<Bitmap> frames = new ArrayList<Bitmap>();

//Create a new Media Player
MediaPlayer mp = MediaPlayer.create(getBaseContext(), myVideoUri);

// Some kind of iteration to retrieve the frames and add it to Array list
Bitmap bitmap = mmRetriever.getFrameAtTime(TIME IN MICROSECONDS);
frames.add(bitmap);

And then create a Drawable Animation programmatically:

AnimationDrawable animatedGIF = new AnimationDrawable();

animationDrawable.addFrame("FIRST FRAME", 50);
animationDrawable.addFrame("SECOND FRAME", 50);
...
animationDrawable.addFrame("LAST FRAME ", 50); 
Sam R.
  • 16,027
  • 12
  • 69
  • 122
8
  1. Import ffmpeg in your project, grab the portion or entire video and convert it to gif.

    or

  2. Use MediaRetriever to extract range of frames with simple looping through the range and then converting to Drawable or Bitmap so you can save it.

    or

  3. Grab the frames while the video is playing from the SurfaceViewHolder or SurfaceView Canvas.

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148