项目中有个需求是将图片保存到相册中,本文整理了该功能如下,记录方便以后使用
String fileName = null; //系统相册目录 String galleryPath= Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM +File.separator+"Camera"+File.separator; //Drawable转换成bitmap GlideBitmapDrawable bd = (GlideBitmapDrawable) drawable; Bitmap bitmap = bd.getBitmap(); // 声明文件对象 File file = null; // 声明输出流 FileOutputStream outStream = null; try { // 如果有目标文件,直接获得文件对象,否则创建一个以filename为名称的文件 String temp = UUID.randomUUID().toString(); file = new File(galleryPath, temp+ ".jpg"); // 获得文件相对路径 fileName = file.toString(); // 获得输出流,如果文件中有内容,追加内容 outStream = new FileOutputStream(fileName); if (null != outStream) { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream); } } catch (Exception e) { e.getStackTrace(); }finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, fileName, null); Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(file); intent.setData(uri); activity.sendBroadcast(intent);