如何从图库中获取图像并将其显示在android sdk中的屏幕上

mik*_*ike 2 sdk android get image

我想知道如何从图库中获取预先保存的图像,然后将其显示在屏幕上.任何教程/有用的链接和信息将不胜感激.如果有什么您希望我解释的更多,请询问.

Joh*_*ick 5

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
Run Code Online (Sandbox Code Playgroud)

此Intent用于从SD卡中拾取图像并onActivityResult()用于获取图像并显示图像ImageView.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
 {
  if (resultCode == RESULT_OK)
  {
    Uri photoUri = data.getData();
    if (photoUri != null)
    {
    try {
          String[] filePathColumn = {MediaStore.Images.Media.DATA};
          Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null); 
     cursor.moveToFirst();
 int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
 String filePath = cursor.getString(columnIndex);
 cursor.close();
 Bitmap bMap = BitmapFactory.decodeFile(filePath);
 image.setImageBitmap(bMap);

 }catch(Exception e)
  {}
  }
}
}
}
Run Code Online (Sandbox Code Playgroud)

现在我们从图库中获取已抛出的图像,然后将图像设置为ImageVIew.image.setImageBitmap(bMap);将图像设置为ImageView.

  • 你应该总是检查是否可以执行cursor.MoveToFirst,否则如果没有返回媒体你会得到一个异常:if(cursor.moveToFirst()){main code} (2认同)