How to create GIF from multiple bitmaps of images in android

The main theme of my application is that the user has to select images from their device gallery and the selected images are converted to GIFs. ... I am converting these selected images to bitmaps and I am using this GIFEncoder.java file to convert the selected images to GIF and I have achieved this. when I check it in my folder the GIF was created, but when I open the GIF there was no animation, a black screen appeared.

Here is my MainActivity looks like this:

public class MainActivity extends AppCompatActivity {

private static final int SELECT_PHOTO = 102;

private FileOutputStream outStream;
ArrayList<Bitmap> bitmaps = new ArrayList<>();
private Button generateImageGIF, selectImages;

String BASE_PATH = Environment.getExternalStorageDirectory().toString() + File.separator + "ImagesToGif";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    File mydir = new File(BASE_PATH);
    if (!mydir.exists()) {
        mydir.mkdirs();
    }

    generateImageGIF = (Button) findViewById(R.id.generate_image_gif);
    selectImages = (Button) findViewById(R.id.select_images);

    selectImages.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, SELECT_PHOTO);
        }
    });

    generateImageGIF.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Toast.makeText(getApplicationContext(), "gif creation started", Toast.LENGTH_LONG).show();
                outStream = new FileOutputStream(BASE_PATH + File.separator + getString(R.string.app_name) + ".gif");
                outStream.write(generateGIF());
                outStream.close();
                Toast.makeText(getApplicationContext(), "gif creation ended", Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
        Bitmap bitmap1 = BitmapFactory.decodeFile(String.valueOf(data.getData()));
        bitmaps.add(bitmap1);
    }
}

public byte[] generateGIF() {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    AnimatedGifEncoder encoder = new AnimatedGifEncoder();
    encoder.start(bos);
    for (Bitmap bitmap : bitmaps) {
        encoder.addFrame(bitmap);
    }
    encoder.finish();
    return bos.toByteArray();
}
}

      

+3


source to share





All Articles