將圖片保存到系統相冊的兩種方法
來源:程序員人生 發布時間:2014-11-09 08:42:15 閱讀次數:2910次
第1種:采取系統的api直接使用:
ContentResolver cr = getContentResolver();
String url = MediaStore.Images.Media.insertImage(cr, bmp,
String.valueOf(System.currentTimeMillis()), "");
但是,這類方式必須得刷新圖庫:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
雖然如此,這類方法還是只能合適安卓4.4以下的手機,若是4.4以上的手機就會報錯,因此建議采取第2種方式來寫;
第2種:直接采取文件流進行保存到相冊
File tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/"
+ String.valueOf(System.currentTimeMillis()) + ".png");
if(tempFile.exists()){
tempFile.delete();
}
try {
tempFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
最后把全部方法貼出來:
/**
*
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
------分隔線----------------------------
------分隔線----------------------------