gpt4 book ai didi

android - 如何从图库中获取所选图像的路径

转载 作者:搜寻专家 更新时间:2023-11-01 08:28:47 27 4
gpt4 key购买 nike

我正在创建一个将图像上传到服务器的应用程序。选择图像时出现以下异常。

方法抛出“android.database.sqlite.SQLiteException”异常..

near "FROM": syntax error (code 1): , while compiling: SELECT  FROM images WHERE (_id=?)

打开图库的代码:

  Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICKER);

关于 Activity 结果

  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));

最佳答案

当您使用 ContentProvider 选择任何图像时,您得到的是该图像的 URI。您需要将此 URI 转换为 *绝对路径*:

您可以使用以下 util 将任何文件的 URI 转换为绝对路径:

public class RealPathUtil {

@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);

// Split at colon, use second item in the array
String id = wholeID.split(":")[1];

String[] column = { MediaStore.Images.Media.DATA };

// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";

Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);

int columnIndex = cursor.getColumnIndex(column[0]);

if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}


@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;

CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();

if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}

public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor 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);
}
}

更多信息,请查看教程here .

关于android - 如何从图库中获取所选图像的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42344154/

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