项目中保存图片到相册这个功能很简单,但是如果有gif就相对难一些,需要判断是否是gif,本文将该功能做相应记录
String imagePath=null; Drawable drawable = mImageView.getDrawable();
//判断图片类型
if (drawable instanceof GifDrawable){
imagePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+System.currentTimeMillis()+".gif";
}else {
imagePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+System.currentTimeMillis()+".png";
}
/**
* 拷贝到指定路径 保存图片和动态图
*/
final String finalImagePath = imagePath;
new Thread(new Runnable() {
@Override
public void run() {
//java.lang.IllegalArgumentException: YOu must call this method on a background thread
//必须在子线程中进行
String path = getImagePath(mImageUrl);
copyFile(path, finalImagePath);
System.out.println("保存地址;"+ finalImagePath);
Intent intentBroadcast = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File(finalImagePath);
intentBroadcast.setData(Uri.fromFile(file));
activity.sendBroadcast(intentBroadcast);
}
}).start();/** * Glide 获得图片缓存路径 */ private String getImagePath(String imgUrl) { String path = null; FutureTarget<File> future = Glide.with(this) .load(imgUrl) .downloadOnly(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL); try { File cacheFile = future.get(); path = cacheFile.getAbsolutePath(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return path; } public void copyFile(String oldPath, final String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldPath); //读入原文件 FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数 文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { ToastUtils.showShortToast(activity,"以保存至"+newPath); } }); } catch (Exception e) { e.printStackTrace(); } }
别忘了添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
该项目详细介绍了如何使用Glide加载图片,并实现将图片包括GIF保存到手机相册的功能。特别地,文章重点讲解了如何判断加载的图片是否为GIF格式。
5332

被折叠的 条评论
为什么被折叠?



