gpt4 book ai didi

java - Android从捕获的图像中获取图像路径

转载 作者:行者123 更新时间:2023-12-01 12:07:17 26 4
gpt4 key购买 nike

我在尝试从捕获的图像获取图像路径时遇到一些问题。当我的相机按钮点击时:

takePickBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(cameraIntent, "Select Picture"), REQUEST_IMAGE_CAPTURE);
}
});

然后是我尝试将捕获的图像加载到 ImageView 并获取字符串以将其传递给异步 Http Post 的代码:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == REQUEST_IMAGE_CAPTURE
&& resultCode == RESULT_OK) {
final ContentResolver cr = getContentResolver();
final String[] p1 = new String[] {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATE_TAKEN
};
Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");
if ( c1.moveToFirst() ) {
String uristringpic = "content://media/external/images/media/" +c1.getInt(0);
Uri uri = Uri.parse(uristringpic);
try {
Bitmap bm = android.provider.MediaStore.Images.Media.getBitmap(cr, uri);
} finally {

}
params.put("filename", uristringpic);
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}

}

但是,通过执行此操作,捕获的图像已设置为 ImageView 。但是当我尝试打印 uristringpic 时,它是空的。有什么想法吗?

提前致谢。

最佳答案

也许你应该尝试这样的事情

Uri photoUri;

takePickBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
photoUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(Intent.createChooser(cameraIntent, "Select Picture"), REQUEST_IMAGE_CAPTURE);
}
});

现在,拍摄图像后,photoUri var 中就有了图像 uri。

如果您需要真实路径,只需使用

public static String getPathFromMediaUri(@NonNull Context context, @NonNull Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}

关于java - Android从捕获的图像中获取图像路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27496050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com