Android调用系统图库获取图片

authorities :一个标识,在当前系统内必须是唯一值,一般用包名。
exported :表示该 FileProvider 是否需要公开出去。
granUriPermissions :是否允许授权文件的临时访问权限。这里需要,所以是 true。
XML文件中的TAG和属性
private static final String TAG_ROOT_PATH = “root-path”;
private static final String TAG_FILES_PATH = “files-path”;
private static final String TAG_CACHE_PATH = “cache-path”;
private static final String TAG_EXTERNAL = “external-path”;
private static final String TAG_EXTERNAL_FILES = “external-files-path”;
private static final String TAG_EXTERNAL_CACHE = “external-cache-path”;

Adnroid中保存图片的方法可能有如

public static File saveImage(Bitmap bmp) {
File appDir = new File(Environment.getExternalStorageDirectory(), “Boohee”);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + “.jpg”;
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
文件名以当前系统时间命名,但是这种方法保存的图片没有加入到系统图库中
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, “title”, “description”);
调用以上系统自带的方法会把bitmap对象保存到系统图库中,但是这种方法无法指定保存的路径和名称,上述方法的title、description参数只是插入数据库中的字段,真实的图片名称系统会自动分配。

更新系统图库的方法
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(“file://”+ Environment.getExternalStorageDirectory())));
或者
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/sdcard/Boohee/image.jpg")));

或者还有如下方法:
final MediaScannerConnection msc = new MediaScannerConnection(mContext, new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msc.scanFile("/sdcard/Boohee/image.jpg", “image/jpeg”);
}
public void onScanCompleted(String path, Uri uri) {
Log.v(TAG, “scan completed”);
msc.disconnect();
}
});

sdk还提供了这样一个方法:
MediaStore.Images.Media.insertImage(getContentResolver(), “image path”, “title”, “description”);
第二个参数是image path首先自己写方法把图片指定到指定的文件夹,然后调用上述方法把刚保存的图片路径传入进去,最后通知图库更新。

代码如下:
public static void saveImageToGallery(Context context, Bitmap bmp) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), “Boohee”);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + “.jpg”;
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(“file://” + path)));
}

你可能感兴趣的:(Android)