从字节数组写入GIF(在Android中)

时间:2013-11-23 09:59:39

标签: java android byte bytearray gif

使用以下代码我尝试将JPEG保存到动画GIF文件中 我是Java和Android开发的新手,并不知道什么是错的 有人可以帮我完成这个吗?

MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource("/path/to/a/sample/file.mp4");

Bitmap b1 = mmr.getFrameAtTime(0);
Bitmap b2 = mmr.getFrameAtTime(100);
Bitmap b3 = mmr.getFrameAtTime(200);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
b1.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray1 = stream.toByteArray();

b2.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray2 = stream.toByteArray();

b3.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray3 = stream.toByteArray();

DataOutputStream writer;
try {
    writer = new DataOutputStream(new FileOutputStream("/path/to/a/sample/output/file.gif"));

    writer.writeBytes("GIF"); //header
    writer.writeBytes("89a");

    writer.write(byteArray1, 0, byteArray1.length); //image 1
    writer.write(byteArray2, 0, byteArray2.length); //image 2
    writer.write(byteArray3, 0, byteArray3.length); //image 3
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

2 个答案:

答案 0 :(得分:1)

老问题,但我刚刚碰巧在同样的事情上工作。 如果您的帧数有限,您可以创建一个gif(我应该说的动画图片):

AnimationDrawable animatedGIF = new AnimationDrawable();
animatedGIF.addFrame(new BitmapDrawable(getResources(), <bitmap1>), <duration>);
animatedGIF.addFrame(new BitmapDrawable(getResources(), <bitmap2>), <duration>);

view.setBackground(animatedGIF); // attach animation to a view
animatedGIF.run();

答案 1 :(得分:0)

错误的是,动画GIF 不是一系列正常的GIF 。而且它也不是PNG(为什么你把它压缩成PNG?好吧无所谓,不管怎样都不行。)

动画GIF格式的基本介绍:http://en.wikipedia.org/wiki/Graphics_Interchange_Format#Animated_GIF

据我所知,标准JRE API不支持创建动画GIF。可能有第三方库支持它。期望编写更多更多代码来执行转换。

相关问题