现在越来越多的项目要用到保存网络图到本地的功能 尤其是一些电商项目。最近做项目注意到一个细节,如果只是保存到本地并不能在相册直接显示出来,需要通知相册更新。
我项目使用的图片加载工具是glide可以很方便的下载图片获取到本地图片地址,如果有时候是bitmap也可以直接保存到本地。
private void saveImageLocal(String imgUrl) { try { File file = null; file = Glide.with(ShowImgsActivity.this).load(imgUrl).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get(); String oldPath = file.getPath(); //Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)就是系统picture路径 File newFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "xxx"); if (!newFile.exists()) { newFile.mkdirs(); } final String name="IMG"+System.currentTimeMillis()+".jpg"; final String newPath = newFile.getPath() + "/" + name; copyFile(oldPath, newPath); // 其次把文件插入到系统图库 就是保存到picture 这里低版本是不能保存的 如果路径已经是picture或者子路径不用再放到图库了 //MediaStore.Images.Media.insertImage(getContentResolver(), newPath, name, null); // 最后通知图库更新 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + newPath))); } catch (Exception e) { e.printStackTrace(); } }