您的位置:首页 > 其它

使用Glide加载的图片保存到相册,保存gif到相册

2018-02-28 09:01 549 查看
项目中保存图片到相册这个功能很简单,但是如果有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" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: