public void saveBitmap() {
Toast.makeText(MainActivity.this, "保存图片成功", 1).show();
String state=Environment.getExternalStorageState();
File file;
try {
if(Environment.MEDIA_MOUNTED.equals(state)){
// 保存图片到SD卡上
file = Environment.getExternalStorageDirectory();
}else{
file =getFilesDir();
}
FileOutputStream stream = new FileOutputStream(file.getPath()+System.currentTimeMillis()+".png");
baseBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Toast.makeText(MainActivity.this, "保存图片成功", 0).show();
// Android设备Gallery应用只会在启动的时候扫描系统文件夹
// 这里模拟一个媒体装载的广播,用于使保存的图片可以在Gallery中查看鿴
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
// intent.setData(Uri.fromFile(Environment.getDataDirectory()));
// sendBroadcast(intent);
stream.flush();
stream.close();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "保存图片失败", 1).show();
e.printStackTrace();
}
}
输出“保存图片失败”, 上面这一句也不会被执行:Toast.makeText(MainActivity.this, "保存图片成功", 1).show();为什么呢?但是把try下面的注释了就能执行到,求解!怎样才能保存在手机内存中?
FileOutputStream stream = new FileOutputStream(file.getPath()+System.currentTimeMillis()+".png");
改成
FileOutputStream stream = new FileOutputStream(file.getAbsolutePath()+"/"+System.currentTimeMillis()+".png");
先检查存储权限,安卓6.0之后存储权限是关闭的,需要你代码去调,然后弹出框让用户授权
直接用图片工具类吧,哪有这么麻烦!https://github.com/AbrahamCaiJin/CommonUtilLibrary
你看下是不是要在Manifest里面加读写sd卡的权限
看看你失败的log文件
adb logcat > saveImgFail.log
怀疑是保存的路径有问题
先前可以现在不可以的情况下,看一下安卓手机权限,每个系统版本都会发生少许的变化
你这是andriod6.0系统以下版本吗?
6.0以上版本是需要动态申请权限的。
已经解决,是路径问题和权限问题,改一个都不行。路径改为:FileOutputStream stream = new FileOutputStream(file.getAbsolutePath()+"/"+System.currentTimeMillis()+".png");权限要在手机设置里面开才行。但是只能采纳一位,谢谢其他人的帮助