我一直在尝试找出如何在Android中将视频文件转换为gif。我在网上找到了一个班级,AnimatedGifEncoder
班级(https://github.com/nbadal/android-gif-encoder/blob/master/GifEncoder.java)。但这似乎并不奏效。我将视频到gif的转换过程包装在AsnycTask
中。代码如下所示:
@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;
}
我的代码是否存在问题(我认为AnimatedGifEncoder
类没有问题)?我也考虑过将文件转换为byte[]
,然后通过byte[]
将GifImageView
提交到Glide
中,但是我想猜测byte []视频不同于gif文件的视频(如果我记错了,请告诉我)?
答案 0 :(得分:2)
您可以在不同的时间找到帧并创建一个可绘制的动画
public void getGIF(){
int counter = 0;
Bitmap b = mmRetriever.getFrameAtTime(counter);
while(counter < duration && b != null){
frame = new BitmapDrawable(getResources(), b);
animationDrawable.addFrame(frame, 50);
counter += incrementor;
b = mmRetriever.getFrameAtTime(counter);
}
}
答案 1 :(得分:0)
您可以像这样使用FFMPEG将视频文件转换为gif:
在您应用的build.gradle中添加
implementation 'nl.bravobit:android-ffmpeg:1.1.7'
然后
var name="sample"
var inFIle = Environment
.getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS).toString() + "/${name}.mp4"
var gifFIle = Environment
.getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS).toString() + "/${name}gif.gif"
val cmd = arrayOf("-i", inFile, gifFIle)
val ffmpeg = FFmpeg.getInstance(baseContext)
ffmpeg.execute(cmd, object : ExecuteBinaryResponseHandler() {
override fun onStart() {
}
override fun onProgress(message: String) {
}
override fun onFailure(message: String) {
}
override fun onSuccess(message: String) {
}
override fun onFinish() {
}
})