我正在开发一个Android项目,我想从Camera或Gallery获取上传图片的路径。所有权限均已设置,我使用此功能获取路径,但似乎createNewFile()
始终被忽略,而我一直都得到path=""
。
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
答案 0 :(得分:0)
您可能使用某种方式来组合文件路径,但这在您的帖子中看不到。您可能错过了清单中的授予权限,因此未创建文件。 试试这个:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
答案 1 :(得分:0)
此行使您的应用无法正常运行
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
将其更改为
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY);
答案 2 :(得分:0)
在尝试访问时,请确保手机中有外置 SD 卡
Environment.getExternalStorageDirectory()