如何从android中的多个图像位图创建GIF

时间:2017-06-22 09:23:58

标签: android image bitmap gif

我的应用程序的主题是,用户必须从他的设备库中选择图像,并将这些选定的图像转换为 GIF。我将这些选定的图像转换为位图和我正在使用这个GIFEncoder.java文件将所选图像转换为GIF,我已经实现了它。当我在我的文件夹中检查它时,GIF已经创建,但是当我打开GIF时没有动画,只是出现了黑屏。

这是我的 MainActivity ,如下所示:

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();
}
}

0 个答案:

没有答案