我一直试图获取捕获图像的路径以删除图像。在StackOverflow上找到了很多答案,但没有一个对我有用。我得到了以下答案:
private String getLastImagePath() {
final String[] imageColumns = { MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = POS.this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
null, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
// int id = imageCursor.getInt(imageCursor
// .getColumnIndex(MediaStore.Images.Media._ID));
String fullPath = imageCursor.getString(imageCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
return fullPath;
} else {
return "";
}
}
此代码适用于Samsung选项卡,但在Lenovo选项卡和i-ball选项卡中不起作用。 那么,任何人都可以帮我找到另一种解决方案吗? 任何帮助将不胜感激。谢谢。
这是我的onActivityResult:
if (requestCode == CmsInter.CAMERA_REQUEST && resultCode == RESULT_OK) {
//Bitmap photo = null;
//photo = (Bitmap) data.getExtras().get("data");
String txt = "";
if (im != null) {
String result = "";
//im.setImageBitmap(photo);
im.setTag("2");
int index = im.getId();
String path = getLastImagePath();
try {
bitmap1 = BitmapFactory.decodeFile(path, options);
bitmap = Bitmap.createScaledBitmap(bitmap1, 512, 400, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytData = baos.toByteArray();
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
result = Base64.encode(bytData);
bytData = null;
} catch (OutOfMemoryError ooM) {
System.out.println("OutOfMemory Exception----->" + ooM);
bitmap1.recycle();
bitmap.recycle();
} finally {
bitmap1.recycle();
bitmap.recycle();
}
}
}
答案 0 :(得分:91)
试试这个
如下所示传递相机意图
Intent intent = new Intent(this);
startActivityForResult(intent, REQ_CAMERA_IMAGE);
捕捉图像后写下OnActivityResult
如下
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) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;
}
并查看日志
编辑:
很多人都在问如何不获取缩略图。您需要为getImageUri
方法添加此代码:
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
另一种方法压缩文件。您可以通过更改数字1000,1000
答案 1 :(得分:10)
有一个创建文件的解决方案(在外部缓存目录或其他任何地方)并将此文件的uri作为输出额外的摄像机意图 - 这将定义拍摄照片的路径。
以下是一个例子:
File file;
Uri fileUri;
final int RC_TAKE_PHOTO = 1;
private void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(getActivity().getExternalCacheDir(),
String.valueOf(System.currentTimeMillis()) + ".jpg");
fileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
getActivity().startActivityForResult(intent, RC_TAKE_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {
//do whatever you need with taken photo using file or fileUri
}
}
}
然后,如果您不再需要该文件,可以使用file.delete();
顺便说一句,当用户从应用程序设置中清除应用程序的缓存时,将删除缓存目录中的文件。
答案 2 :(得分:2)
尝试使用此方法获取相机捕获的original
图像的路径。
public String getOriginalImagePath() {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
return cursor.getString(column_index_data);
}
此方法将返回相机捕获的最后一张图像的路径。因此,此路径为原始图片,而不是缩略图位图。
答案 3 :(得分:2)
在这里,我更新了Kotlin中的示例代码。请注意关于Nougat和以上版本Uri.fromFile(file)
不起作用,它崩溃了应用程序,因为需要实现FileProvider,这是从intent发送文件最安全的方法。要实现此功能,请参阅此answer或此article
private fun takePhotoFromCamera() {
val isDeviceSupportCamera: Boolean = this.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
if (isDeviceSupportCamera) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS + "/attachments")!!.path,
System.currentTimeMillis().toString() + ".jpg")
// fileUri = Uri.fromFile(file)
fileUri = FileProvider.getUriForFile(this, this.applicationContext.packageName + ".provider", file!!)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
startActivityForResult(takePictureIntent, Constants.REQUEST_CODE_IMAGE_CAPTURE)
}
} else {
Toast.makeText(this, this.getString(R.string.camera_not_supported), Toast.LENGTH_SHORT).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if(requestCode == Constants.REQUEST_CODE_IMAGE_CAPTURE) {
realPath = file?.path
//do what ever you want to do
}
}
}
答案 4 :(得分:0)
相机应用程序会自动保存图像并获取该图像,我们可以执行以下操作:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Uri imgUri = data.getData();
String realPath = getRealPathFromURI(imgUri);
}
}
和getRealPathFromUri方法是:
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);
}
答案 5 :(得分:0)
请参阅Google文档: Camera - Photo Basics
答案 6 :(得分:-1)
试试这个
String[] projection = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
image_path = cursor.getString(column_index_data);
Log.e("path of image from CAMERA......******************.........",
image_path + "");
用于捕获图像:
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
values.clear();