前提:必须依赖Glide中的三个类,AnimatedGifEncoder、LZWEncoder、NeuQuant
缺点:图片越多,生成的GIF尺寸越大,制作的时间更久
public class MakeGifUtil {
/**
* 将本地多张图片制作为gif图
*
* @param foldName 需要保存的gif所在目录
* @param filename 需要保存的gif文件名
* @param paths 制作gif的图片本地路径
* @param fps 图片切换的速度,单位为毫秒
* @param width gif的宽度
* @param height gif的高度
* @return gif最后的绝对路径
* @throws IOException
*/
public static String createGifByPaths(String foldName, String filename, List<String> paths, int fps, int width, int height) throws IOException {
List<Bitmap> bitmaps = new ArrayList<>();
if (paths.size() > 0) {
for (int i = 0; i < paths.size(); i++) {
Bitmap bitmap = BitmapFactory.decodeFile(paths.get(i));
bitmaps.add(bitmap);
}
}
String path = createGifByBitmapList(foldName, filename, bitmaps, fps, width, height);
return path;
}
public static String createGifByBitmaps(String foldName, String filename, List<Bitmap> bitmaps, int fps, int width, int height) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
AnimatedGifEncoder gifEncoder = new AnimatedGifEncoder();
gifEncoder.start(baos);//start
gifEncoder.setRepeat(0);//设置生成gif的开始播放时间。0为立即开始播放
gifEncoder.setDelay(fps);
LogUtil.println("开始制作GIF:" + DateUtil.longToMill(System.currentTimeMillis()));
if (bitmaps.size() > 0) {
for (int i = 0; i < bitmaps.size(); i++) {
//缩放bitmap
Bitmap resizeBm = BitmapUtil.resizeImage(bitmaps.get(i), width, height);
gifEncoder.addFrame(resizeBm);
}
}
gifEncoder.finish();//finish
LogUtil.println("GIF制作完成:" + DateUtil.longToMill(System.currentTimeMillis()));
String path = foldName + filename;
FileOutputStream fos = new FileOutputStream(path);
baos.writeTo(fos);
baos.flush();
fos.flush();
baos.close();
fos.close();
return path;
}
}
BitmapUtil:
//使用Bitmap加Matrix来缩放
public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// if you want to rotate the Bitmap
// matrix.postRotate(45);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
height, matrix, true);
return resizedBitmap;
}