Java 如何在Android中检测给定图像文件是否为动画GIF
我正在写一个图像编辑器 我不支持编辑动画gif,因此当用户选择图像时,如果该图像是动画gif,我需要显示错误消息 那么给定一个文件路径,我如何区分静态gif和动画gif呢 我检查了这个问题,但它不适用于Android,因为ImageIO类不可用Java 如何在Android中检测给定图像文件是否为动画GIF,java,android,image,animation,gif,Java,Android,Image,Animation,Gif,我正在写一个图像编辑器 我不支持编辑动画gif,因此当用户选择图像时,如果该图像是动画gif,我需要显示错误消息 那么给定一个文件路径,我如何区分静态gif和动画gif呢 我检查了这个问题,但它不适用于Android,因为ImageIO类不可用 注意:我只需要知道是否设置了动画,所以我希望使用最快的方法。下面的代码对我有效: 使用图像http url进行检查 URL url = new URL(path); URLConnection conn = url.openConnection(); I
注意:我只需要知道是否设置了动画,所以我希望使用最快的方法。下面的代码对我有效: 使用图像http url进行检查
URL url = new URL(path);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inputStream.close();
byte[] bytes = outStream.toByteArray();
Movie gif = Movie.decodeByteArray(bytes, 0, bytes.length);
//If the result is true, its a animated GIF
if (gif != null) {
return true;
} else {
return false;
}
或通过从库中选择文件进行检查:
try {
//filePath is a String converted from a selected image's URI
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
fileInputStream.close();
byte[] bytes = outStream.toByteArray();
Movie gif = Movie.decodeByteArray(bytes, 0, bytes.length);
//If the result is true, its a animated GIF
if (gif != null) {
type = "Animated";
Log.d("Test", "Animated: " + type);
} else {
type = "notAnimated";
Log.d("Test", "Animated: " + type);
}
} catch (IOException ie) {
ie.printStackTrace();
}
Movie
类来自何处?它是一个android默认类,请查看:[link]该类在API级别28中被弃用。喜欢动画图像绘制。