I've been trying to figure out how to convert a video file to a gif in android. I found a class online, the AnimatedGifEncoder
class (https://github.com/nbadal/android-gif-encoder/blob/master/GifEncoder.java). But it doesn't really seem to work. I wrapped the video to gif conversion process in an AsnycTask
. The code is shown below:
@Override
protected String doInBackground(File[] files) {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
try {
mmr.setDataSource(files[0].getPath());
} catch (Exception e){
Log.i("VMPF", e.toString());
}
//int framesRate = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE));
int duration = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
Log.i("gifduration","" + duration);
//Log.i("giffps","" + framesRate);
int millisPerframe = 1000/24;
int timeAt = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.setDelay(0);
encoder.setRepeat(100);
encoder.start(bos);
while (timeAt < duration){
encoder.addFrame(mmr.getFrameAtTime(timeAt));
timeAt += millisPerframe;
Log.i("wenfhluwhru", timeAt+"");
}
encoder.finish();
Log.i("wenfhluwhru", "loop finished");
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(path);
outStream.write(bos.toByteArray());
outStream.close();
Log.i("wenfhluwhru", "outstream closed");
return path;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
Is there something wrong with my code (I assume they're nothing wrong with the AnimatedGifEncoder
class)? Also I thought about converting a file to a byte[]
and just submitting the byte[]
into the GifImageView
via Glide
but I'm willing to guess that the byte[] for a video is different from that of a gif file (if I'm wrong, please let me know)?