我试图创建一个非常简单的应用程序,允许用户在提供的图像上书写并将其保存到他们的图库中。我尝试了下面的代码。它会触发错误,无法保存图像。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.savebutton:
Bitmap bitmap = ((BitmapDrawable)imagecp.getDrawable()).getBitmap();
saveBitmap(bitmap);
default:
return super.onOptionsItemSelected(item);
}
public void saveBitmap(Bitmap bmp) {
String _time = "";
Calendar cal = Calendar.getInstance();
int millisecond = cal.get(Calendar.MILLISECOND);
int second = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);
int hourofday = cal.get(Calendar.HOUR_OF_DAY);
_time = "image_" + hourofday + "" + minute + "" + second + ""
+ millisecond + ".png";
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath();
try {
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, _time);
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, fOut);
fOut.flush();
fOut.close();
Toast.makeText(getApplicationContext(),
"Image has been saved in Couponmaker folder",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"saving failed",
Toast.LENGTH_LONG).show();
Log.e("error in saving image", e.getMessage());
}
}
和错误消息
E/error in saving image﹕ /storage/0C11-3814/image_162259256.png: open failed: EACCES (Permission denied)
W/EGL_emulation﹕ eglSurfaceAttrib not implemented
W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad78df60, error=EGL_SUCCESS
E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7dd67 W/art﹕ Suspending all threads took: 13.866ms
xml文件
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"....
答案 0 :(得分:0)
我相信Marshmallow,外部设备目录是sd卡目录。我试图在SD卡上写但是失败了。因为他们不允许这样做(我读到某处但是因为我忘记了所以我不能在这里添加链接)。图库不一定从外部存储中读取图像。看看这个答案,可能有助于解决您的问题:How to save image in android gallery