在Android上获取图像的文件路径 [英] Get file path of image on Android
问题描述
我有一个可以制作图片并上传的应用程序.上传需要照片的文件路径,但我无法获取.
I have an app that can make pictures and upload them. The upload requires the file path of the photo but I can't get it.
这是我的代码:
public void maakfoto (View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
}
}
请帮我获取文件路径.
推荐答案
发布到 Twitter 需要在要发布的请求中发送图像在设备上的实际路径.我发现获取实际路径非常困难,而且我经常会得到错误的路径.
Posting to Twitter needs the image's actual path on the device to be sent in the request to post. I was finding it mighty difficult to get the actual path and more often than not I would get the wrong path.
为了解决这个问题,一旦你有了 Bitmap
,我就用它来通过 getImageUri()
来获取 URI.随后,我使用 tempUri
Uri 实例来获取设备上的实际路径.
To counter that, once you have a Bitmap
, I use that to get the URI from using the getImageUri()
. Subsequently, I use the tempUri
Uri instance to get the actual path as it is on the device.
这是生产代码,经过自然测试.;-)
This is production code and naturally tested. ;-)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
这篇关于在Android上获取图像的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!