在Android上获取图像的文件路径
Posted
技术标签:
【中文标题】在Android上获取图像的文件路径【英文标题】:Get file path of image on Android 【发布时间】:2013-03-04 04:17:07 【问题描述】:我有一个可以制作图片并上传的应用程序。上传需要照片的文件路径,但是我获取不到。
这是我的代码:
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);
请帮我获取文件路径。
【问题讨论】:
***.com/questions/9564538/…希望这会有所帮助 @MaikelR 你能帮我解决这个详细的赏金问题吗?非常感谢:***.com/questions/62783444/… 【参考方案1】:如果你以后需要 kotlin 代码,你可以在 Kotlin 中这样做
val myUri = getImageUri(applicationContext, myBitmap!!)
val finalFile = File(getRealPathFromURI(myUri))
fun getImageUri(inContext: Context, inImage: Bitmap): Uri
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
return Uri.parse(path)
fun getRealPathFromURI(uri: Uri): String
val cursor = contentResolver.query(uri, null, null, null, null)
cursor!!.moveToFirst()
val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
return cursor.getString(idx)
【讨论】:
【参考方案2】:要获取android中所有图像的路径,我使用以下代码
public void allImages()
ContentResolver cr = getContentResolver();
Cursor cursor;
Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Images.Media._ID + " != 0";
cursor = cr.query(allsongsuri, STAR, selection, null, null);
if (cursor != null)
if (cursor.moveToFirst())
do
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
Log.i("Image path ", fullpath + "");
while (cursor.moveToNext());
cursor.close();
【讨论】:
【参考方案3】:Simple Pass Intent first
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
你会在你的onActivityResult上得到图片路径
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
Uri selectedImage = data.getData();
String[] filePathColumn = MediaStore.Images.Media.DATA ;
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
【讨论】:
【参考方案4】:使用该函数获取抓图路径
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
Uri mImageCaptureUri = intent.getData();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
//getImgPath(mImageCaptureUri);// it will return the Capture image path
public String getImgPath(Uri uri)
String[] largeFileProjection = MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA ;
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try
myCursor.moveToFirst();
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
finally
myCursor.close();
return largeImagePath;
【讨论】:
【参考方案5】:我在单击按钮时执行此操作。
private static final int CAMERA_PIC_REQUEST = 1;
private View.OnClickListener OpenCamera=new View.OnClickListener()
@Override
public void onClick(View paramView)
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
NewSelectedImageURL=null;
//outfile where we are thinking of saving it
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String newPicFile = RecipeName+ df.format(date) + ".png";
String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
File outFile = new File(outPath);
CapturedImageURL=outFile.toString();
Uri outuri = Uri.fromFile(outFile);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
;
您可以从变量CapturedImageURL获取最近捕获的图像的URL
protected void onActivityResult(int requestCode, int resultCode, Intent data)
//////////////////////////////////////
if (requestCode == CAMERA_PIC_REQUEST)
// do something
if (resultCode == RESULT_OK)
Uri uri = null;
if (data != null)
uri = data.getData();
if (uri == null && CapturedImageURL != null)
uri = Uri.fromFile(new File(CapturedImageURL));
File file = new File(CapturedImageURL);
if (!file.exists())
file.mkdir();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
【讨论】:
【参考方案6】:发帖到 Twitter 需要在发帖请求中发送图片在设备上的实际路径。我发现获取实际路径非常困难,而且我经常会走错路径。
为了解决这个问题,一旦你有了Bitmap
,我就会使用它来通过getImageUri()
获取URI。随后,我使用tempUri
Uri 实例来获取设备上的实际路径。
这是生产代码,经过自然测试。 ;-)
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);
【讨论】:
我收到“未能提供‘结果’。 @RickdeJong:您使用的代码与帖子中的完全一样吗?因为如果你是,它应该可以工作。 @iceMAN 你拯救了我的一天:) @IceMAN:我发现getData("data")
我们只返回图像的缩略图,见这里:***.com/questions/6448856/…。我能够暂时保存图像,然后稍后抓取以解决此问题。无论如何,谢谢。
记得关闭光标【参考方案7】:
通过以下方式尝试mImageCaptureUri.getPath();
:
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
//Get your Image Path
String Path=mImageCaptureUri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
【讨论】:
当我这样做时应用程序会崩溃。 这可能是因为 mImageCaptureUri 没有在全局范围内定义和初始化。尝试全局定义它。并在为 captureimage 设置意图时将其传递给 putextra。【参考方案8】:为了拍照,您必须确定要保存图像的路径,并将其作为额外的 Intent 传递,例如:
private void capture()
String directoryPath = Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY + "/";
String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".jpg";
File directory = new File(directoryPath);
if (!directory.exists())
directory.mkdirs();
this.capturePath = filePath; // you will process the image from this path if the capture goes well
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(filePath) ) );
startActivityForResult(intent, REQUEST_CAPTURE);
我刚刚从我给出的另一个答案中复制了上述部分。
但是提醒您,您应该注意设备之间的图像捕获行为有很多不一致之处。
这是我在某些 HTC 设备上遇到的问题,它会保存在我通过的位置和默认位置,从而导致设备上出现重复图像: Deleting a gallery image after camera intent photo taken
【讨论】:
以上是关于在Android上获取图像的文件路径的主要内容,如果未能解决你的问题,请参考以下文章