问题描述
我正在尝试从相机或图库中获取图像以上传到服务器上。我的代码在Android 9或更低版本的Android 9上可以正常运行,但是我无法在Android 10上访问图像路径。我对Android 10的范围存储了解不多,请查看我的代码和帮助。
private void selectimage(Context context,final int cameraRequestCode,final int galleryRequestCode) {
if (!hasPermissions(context,PERMISSIONS)) {
ActivityCompat.requestPermissions(requireActivity(),PERMISSIONS,PERMISSION_ALL);
} else {
final CharSequence[] options = {"Take Photo","Choose from gallery","Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int item) {
if (options[item].equals("Take Photo")) {
/* Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture,cameraRequestCode);*/
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);
startActivityForResult(intent,cameraRequestCode);
} else if (options[item].equals("Choose from gallery")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto,galleryRequestCode);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
public File convertBitmaptoFile(Bitmap bitmap,String filename) throws IOException {
File f = new File(requireContext().getCacheDir(),filename);
f.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100 /*ignored for PNG*/,bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
return f;
}
“这是我的onActivity代码”
@Override
public void onActivityResult(int requestCode,int resultCode,Intent data) {
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
try {
String millisecond = String.valueOf(Calendar.getInstance().getTimeInMillis());
// logo_file = new File(String.valueOf(convertBitmaptoFile(filetoBitmap(sdImageMainDirectory.getPath()),"IMAGE_" + millisecond + ".jpg")));
// img_logo.setimageURI(Uri.parse(logo_file.getAbsolutePath()));
img_logo.setimageURI(Uri.parse(getPath(Uri.fromFile(logo_file = new File(String.valueOf(convertBitmaptoFile(filetoBitmap(sdImageMainDirectory.getPath()),"IMAGE_" + millisecond + ".jpg")))))));
Log.e("logo file path","" + logo_file.getPath());
Log.e("logo file absolute path","" + logo_file.getAbsolutePath());
} catch (IOException e) {
e.printstacktrace();
}
// fa_image.setimageURI(Uri.parse(fa_image_file.getPath()));
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = Uri.parse(data.getData().getEncodedpath());
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getActivity().getContentResolver().query(selectedImage,filePathColumn,null,null);
if (cursor != null) {
cursor.movetoFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
logo_file = new File(picturePath);
Log.e("IMAGE","ja_image :" + logo_file);
img_logo.setimageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}
}
break;
}
}
}
解决方法
您是否已在AndroidManifest.xml中使用了android:requestLegacyExternalStorage =“ true”
<application
android:name="com.xyz"
android:allowBackup="true"
android:exported="false"
android:hardwareAccelerated="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning"
tools:targetApi="q">
,
在 Android 10 中,您无法使用 onActivityResult 中提供的 uri 访问图像。试试这个。我相信它对你有用。当您从图库中选择图像时,这将起作用。对于从相机照片中拍摄照片,方法略有不同。
科特林解决方案:
val imageType = contentResolver.getType(data.data!!)
data.data!!.let {
application.contentResolver.openInputStream(it).use { inputStream ->
filePartImage = MultipartBody.Part.createFormData(
"image",//should be same as the key of your parameter
"filename" + ".jpg",// extension of file name is must
inputStream!!.readBytes().toRequestBody(imageType.toMediaTypeOrNull())
)
}
}
稍后将此 filePartImage 作为您的图像参数传递,以将图像上传到服务器。