How to create an animated GIF from JPEGs in Android (development)
I am looking for a simple way to create an animated GIF in a native Android application. The source files should be JPEG (from camera or what ever) and the output should be saved as GIF on the device.
I do not want to know how to play animations or animated GIF files.
To be clear: I want to know how to put single images frame by frame into a "movie" and then save it as a .gif file.
e.g. This App can do want I want to do.
Solution 1:
See this solution.
https://github.com/nbadal/android-gif-encoder
It's an Android version of this post.
http://www.jappit.com/blog/2008/12/04/j2me-animated-gif-encoder/
To use this class, here is an example helper method to generate GIF byte array. Note here the getBitmapArray() function is a method to return all the Bitmap files in an image adapter at once. So the input is all the Bitmap files in one adapter, the output is a byte array which you can write to the file.
public byte[] generateGIF() {
ArrayList<Bitmap> bitmaps = adapter.getBitmapArray();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
To use this function, do the following then you can save the file into SDcard.
FileOutputStream outStream = null;
try{
outStream = new FileOutputStream("/sdcard/generate_gif/test.gif");
outStream.write(generateGIF());
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
Solution 2:
This might help you. It's a class which is used to generate gif files.
http://elliot.kroo.net/software/java/GifSequenceWriter/
Solution 3:
It did very well for me, It create file fast and good quality images
//True for dither. Will need more memory and CPU
AnimatedGIFWriter writer = new AnimatedGIFWriter(true);
OutputStream os = new FileOutputStream("animated.gif");
Bitmap bitmap; // Grab the Bitmap whatever way you can
// Use -1 for both logical screen width and height to use the first frame dimension
writer.prepareForWrite(os, -1, -1)
writer.writeFrame(os, bitmap);
// Keep adding frame here
writer.finishWrite(os);
// And you are done!!!
https://github.com/dragon66/android-gif-animated-writer
Solution 4:
If you only want to display these bitmaps like an animated gif, you can create an AnimatedDrawable using this code:
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.image1), 10);
animation.addFrame(getResources().getDrawable(R.drawable.image2), 50);
animation.addFrame(getResources().getDrawable(R.drawable.image3), 30);
animation.setOneShot(false);
ImageView imageAnim = (ImageView) findViewById(R.id.imageView);
imageAnim.setImageDrawable(animation);
// start the animation!
animation.start();