最近项目需要把二维码保存到本地,代码如下:
public static String saveBitmap(Bitmap bitmap) {
try {
// 获取内置SD卡路径
String sdCardPath = Environment.getExternalStorageDirectory().getPath();
// 图片文件路径
File file = new File(sdCardPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
File file1 = files[i];
String name = file1.getName();
if (name.endsWith("twocode.png")) {
boolean flag = file1.delete();
LogUtils.print("删除 + " + flag);
}
}
String filePath = sdCardPath + "/twocode.png";
file = new File(filePath);
FileOutputStream os = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
//把文件插入到系统图库
MediaStore.Images.Media.insertImage(App.getApp().getContentResolver(),
file.getAbsolutePath(), "twocode.png", null);
//保存图片后发送广播通知更新数据库
Uri uri = Uri.fromFile(file);
App.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
Toast.makeText(App.getApp(),"二维码保存成功",Toast.LENGTH_SHORT).show();
return filePath;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
希望对大家有帮助