如何从图库中获取图像并在Android Studio中的ImageView中显示

时间:2019-01-08 10:29:27

标签: java android image

在编写此代码时,图库会打开,并且图像已选中,但无法在我们的Android应用程序的图像视图中显示。

这是我的MainActivity.java代码:-

 public class Main3Activity extends AppCompatActivity {
    public static final int GALLERY_PIC = 1;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        Button buttonupload_pic =  findViewById(R.id.buttonupload_pic);
        buttonupload_pic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, GALLERY_PIC);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_PIC && 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 imagepic=  findViewById(R.id.imagepic);
            imagepic.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }


    }
    }

这是xml代码:-

<ImageView
    android:id="@+id/imagepic"
    android:layout_width="216dp"
    android:layout_height="156dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="81dp"
    android:layout_weight="1"></ImageView>

<Button
    android:id="@+id/buttonupload_pic"
    android:layout_width="wrap_content"
    android:layout_height="36dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="247dp"
    android:text="Upload Photo"
    android:layout_gravity="center"
    android:layout_weight="0"/>

这些是我包括的权限:-

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

由于我是Android Studio的新手,请从头开始讲述它

0 个答案:

没有答案