在我的应用中,用户可以选择保存在内存中的图像。
如果我选择内部存储器中的图像,我的代码可以正常工作,但是如果我选择云端的图像(驱动器或照片),则它不起作用并保存0位图像。
代码在片段中。
这是我的代码的一部分:
首先,我用
选择图像 Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
然后,我用
保存图像 Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Bitmap imageSelect = BitmapFactory.decodeFile(picturePath);
cursor.close();
ContextWrapper cw = new ContextWrapper(getContext());
File directory = cw.getDir("images",Context.MODE_PRIVATE);
File myPath = new File(directory,"defaultwallpaper.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
imageSelect.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
if (fos!=null){
fos.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
我有这个错误:
E/BitmapFactory: Unable to decode stream: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
答案 0 :(得分:0)
我通过更改代码解决了这个问题,它适用于我的Nexus 5和Android 6:
Uri uri = data.getData();
/*String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
imageSelect = BitmapFactory.decodeFile(picturePath);
cursor.close();*/
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}