做creator游戏开发时,有需求保存图片到相册目录
接触安卓不多,如有错误欢迎大佬指出。。。
//文件保存到相册
public static void savePhotoFile(String fromPath) {
File fromFile = new File(fromPath);
if(!fromFile.exists()) {
System.out.println("源文件不存在");
return;
}
if (!fromFile.isFile()){
System.out.println("源文件不是文件");
return;
}
try {
//方法一
//复制文件到指定目录下
String toPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "DCIM/Camera/";
File toFile = new File(toPath);
if (!toFile.exists()) {
toFile.mkdir();//没有该目录,创建一个
}
FileInputStream fromStream = new FileInputStream(fromPath); //读入原文件
FileOutputStream toStream = new FileOutputStream(toPath + fromFile.getName());
byte[] buffer = new byte[1024];
int len;
while ((len= fromStream.read(buffer)) > 0){
toStream.write(buffer, 0, len);
}
fromStream.close();
toStream.flush();
toStream.close();
//刷新相册
Context context = AppActivity.getContext();
MediaStore.Images.Media.insertImage(context.getContentResolver(),fromFile.getAbsolutePath(), fromFile.getName(), null);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(new File(toPath));
intent.setData(uri);
context.sendBroadcast(intent);
fromFile.delete();//删除源文件
//方法二
//获得源文件路径,直接把插入到系统图库,可能并不是DCIM目录下
/*Context context = AppActivity.getContext();
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
fromFile.getAbsolutePath(), fromFile.getName(), null);
} catch (Exception e) {
e.printStackTrace();
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(fromFile.getParent()))));*/
} catch (Exception e) {
e.printStackTrace();
}
}