[在Android上使用AnimatedGifEncoder生成Gif

问题描述 投票:0回答:1

我想用AnimatedGifEncoder创建一个gif文件,它的工作成功创建了我的gif,但是我无法更改帧和其他设置(如质量等)之间的延迟。

还有其他人在android上使用此类吗?

这是我的代码:

public final class CreateGifUtil extends AbstractAnimatedResource {
private String filename = null;

public CreateGifUtil(Context ctx, List<QueueItem> queueItems) {
    super(ctx, queueItems);
}

@Override
public void generate() {
    if (!queueItems.isEmpty()) {
        AnimatedGifEncoder encoder = new AnimatedGifEncoder();

        BufferedOutputStream bs = null;
        try {
            File mediaSrc = ResourceUtil.getOutputFolder(ctx, ResourceUtil.Folder.IMAGES);
            String filename = "test" + String.valueOf(System.currentTimeMillis()) + ".gif";
            outputFile = new File(mediaSrc.getAbsolutePath(), filename);
            bs = new BufferedOutputStream(new FileOutputStream(outputFile));
            encoder.start(bs);
            if (isUseFps()) {
                encoder.setFrameRate(getFps());
            }
            encoder.setRepeat(2);
            encoder.setQuality(getQuality());
            for (QueueItem item : queueItems) {
                if (isUseDelayTime()) {
                    encoder.setDelay(getDelayTime());
                }
            encoder.addFrame(getBitmapFromResource(item.getFilepath(), 1));
            }
            boolean result = encoder.finish();
            Log.e("123", String.valueOf(result));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (bs != null) {
                try {
                    bs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

private Bitmap getBitmapFromResource(String filePath, int sampleSize) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = sampleSize;
        return BitmapFactory.decodeFile(filePath, options);
    }
}

这是我的代码:

package autoshooter.draegerit.de.autoshooter.video;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import autoshooter.draegerit.de.autoshooter.queue.QueueItem;
import autoshooter.draegerit.de.autoshooter.util.ResourceUtil;

public final class CreateGifUtil extends AbstractAnimatedResource {

private String filename = null;

public CreateGifUtil(Context ctx, List<QueueItem> queueItems) {
    super(ctx, queueItems);
}

@Override
public void generate() {
    if (!queueItems.isEmpty()) {
        AnimatedGifEncoder encoder = new AnimatedGifEncoder();

        BufferedOutputStream bs = null;
        try {
            File mediaSrc = ResourceUtil.getOutputFolder(ctx, ResourceUtil.Folder.IMAGES);

            String filename = "test" + String.valueOf(System.currentTimeMillis()) + ".gif";

            outputFile = new File(mediaSrc.getAbsolutePath(), filename);
            bs = new BufferedOutputStream(new FileOutputStream(outputFile));
            encoder.start(bs);

            if (isUseFps()) {
                encoder.setFrameRate(getFps());
            }

            encoder.setRepeat(2);
            encoder.setQuality(getQuality());

            for (QueueItem item : queueItems) {
                if (isUseDelayTime()) {
                    encoder.setDelay(getDelayTime());
                }
                encoder.addFrame(getBitmapFromResource(item.getFilepath(), 1));
            }




            boolean result = encoder.finish();
            Log.e("123", String.valueOf(result));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (bs != null) {
                try {
                    bs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

private Bitmap getBitmapFromResource(String filePath, int sampleSize) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = sampleSize;
    return BitmapFactory.decodeFile(filePath, options);
}

}

android gif
1个回答
0
投票

我建议您使用此库Android NDK GIF LibraryAnimatedGifEncoder更好:

这是如何生成GIF文件并将其保存到图库中的完整示例:

@SuppressLint("StaticFieldLeak")
    public class GenerateSaveGIF extends AsyncTask<Void, Integer, String> {
        Context mContext;
        String imageFileName = "APP_" + System.currentTimeMillis() + ".gif";
        ArrayList<BitmapGIFUtil> arrayListBitmaps = new ArrayList<>();
        boolean isSavingBitmapsFinished = false;

        GenerateSaveGIF(Context context) {
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //Preparing;
            // Display ProgressDialog here 
        }

        @SuppressLint("WrongThread")
        @Override
        protected String doInBackground(Void... voids) {
            File storageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                            + "/APP_FOLDER");
            boolean success = true;
            if (!storageDir.exists()) {
                success = storageDir.mkdirs();
            }
            if (success) {
                File imageFile = new File(storageDir, imageFileName);
                savedImagePath = imageFile.getAbsolutePath();
                FileOutputStream outStream = null;
                try {
                    generateGIF(getArrayBitmaps(), savedImagePath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                galleryAddPic(savedImagePath);
            }
            return savedImagePath;
        }

        ArrayList<BitmapGIFUtil> getArrayBitmaps() {
            for (int i = 0; i < mDrawableGif.getNumberOfFrames(); ++i) {
                int GIFDelay = mDrawableGif.getFrameDuration(i); //CHANGE IT IF YOU WANT 
                try {
                    Thread.sleep(GIFDelay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //replace createEachFrame() with your method getBitmapFromResource(); 
                arrayListBitmaps.add(new BitmapGIFUtil(createEachFrame(), GIFDelay));
            }
            isSavingBitmapsFinished = true;
            return arrayListBitmaps;
        }

        void generateGIF(ArrayList<BitmapGIFUtil> arrayList, String path) {
            GifEncoder gifEncoder = new GifEncoder();
            try {
                gifEncoder.init(arrayList.get(0).getBitmap().getWidth(), arrayList.get(0).getBitmap().getHeight(), path, GifEncoder.EncodingType.ENCODING_TYPE_SIMPLE_FAST);
                for (int i = 0; i < arrayList.size(); i++) {
                    gifEncoder.encodeFrame(arrayList.get(i).getBitmap(), arrayList.get(i).getDelay());
                }
                gifEncoder.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(this, getResources().getString(R.string.gif_saved), Toast.LENGTH_SHORT).show();
        }
    }

通知画廊:

 private void galleryAddPic(String imagePath) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(imagePath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        sendBroadcast(mediaScanIntent);
    } 

BitmapGIFUtil类:

    public class BitmapGIFUtil {
    private Bitmap bitmap;
    private int Delay;

    public BitmapGIFUtil() {
    }

    public BitmapGIFUtil(Bitmap bitmap, int delay) {

        this.bitmap = bitmap;
        Delay = delay;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    public int getDelay() {
        return Delay;
    }

    public void setDelay(int delay) {
        Delay = delay;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.