android select image from sdcard [duplicate]

2019-07-20 15:30发布

问题:

This question already has an answer here:

  • How to pick an image from gallery (SD Card) for my app? 10 answers

I have an imageview with a default image, I want when user click the imageview to open an image selector then he selects his image from sdcard then the image is being on the imageview,

this is my imageview

xml

<ImageView
            android:id="@+id/ivImage"
            android:layout_width="100dip"
            android:layout_height="100dip"
            android:layout_marginLeft="10dip"
            android:contentDescription="@string/iv_undefinedImage"
            android:src="@drawable/undefinedimage" />

Java

ImageView iv ;
iv_image = (ImageView)findViewById(R.id.iv_signup_image);
        iv_image.setOnClickListener(this);
public void onClick(View v) {
switch (v.getId()) {
        case R.id.iv_signup_image:
break;
}

回答1:

I think this is what you are looking for

if (Environment.getExternalStorageState().equals("mounted")) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_PICK);
    startActivityForResult(
        Intent.createChooser(
            intent,
            "Select Picture:"),
        requestCode);
}

and to handle the callback

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri selectedImageUri = data.getData();
    String selectedImagePath = getPath(selectedImageUri);
    Bitmap photo = getPreview(selectedImagePath);
}


public String getPath(Uri uri) {
    String res = null;
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().getContentResolver().query(uri, proj, null, null, null);
    if(cursor.moveToFirst()){;
        int column_index = cursor.getColumnIndexOrThrow(proj[0]);
        res = cursor.getString(column_index);
    }
    cursor.close();
    return res;
}

public Bitmap getPreview(String fileName) {
    File image = new File(fileName);

    BitmapFactory.Options bounds = new BitmapFactory.Options();
    bounds.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(image.getPath(), bounds);
    if ((bounds.outWidth == -1) || (bounds.outHeight == -1)) {
        return null;
    }
    int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
        : bounds.outWidth;
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = originalSize / 64;
    return BitmapFactory.decodeFile(image.getPath(), opts);
}

hope it helps



回答2:

Try out the below code.

public class MainActivity extends Activity {
ImageView iv_image,img1;
int column_index;
  Intent intent=null;
// Declare our Views, so we can access them later
String logo,imagePath,Logo;
Cursor cursor;
//YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int SELECT_PICTURE = 1;

 String selectedImagePath;
//ADDED
 String filemanagerstring;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    img1= (ImageView)findViewById(R.id.image1);
    iv_image= (ImageView)findViewById(R.id.iv_signup_image);

    img1.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            // in onCreate or any event where your want the user to
            // select a file
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,
                    "Select Picture"), SELECT_PICTURE);
       }
    });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();

            //OI FILE Manager
            filemanagerstring = selectedImageUri.getPath();

            //MEDIA GALLERY
            selectedImagePath = getPath(selectedImageUri);


            img.setImageURI(selectedImageUri);

           imagePath.getBytes();
           TextView txt = (TextView)findViewById(R.id.title);
           txt.setText(imagePath.toString());

           Bitmap bm = BitmapFactory.decodeFile(imagePath);
           iv_image.setImageBitmap(bm);



        }

    }

}

//UPDATED!
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
        .getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
 imagePath = cursor.getString(column_index);

return cursor.getString(column_index);
}

}

I hope it will help you.

Thanks.



回答3:

private final int GET_USER_IMAGE_FROM_GALLERY = 10;

ImageView imageView = findViewById(R.id.ivImage);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
        "Select Picture"),
GET_USER_IMAGE_FROM_GALLERY);
});


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

if (requestCode == GET_USER_IMAGE_FROM_GALLERY) {

        if (data != null) {

            Uri selectedImageUri = data.getData();
            String selectedImagePath = getPath(selectedImageUri);

            try {
                File imageFile = new File(selectedImagePath);
                Bitmap bitmap = BitmapFactory.decodeFile(imageFile
                        .getAbsolutePath());

                imageView.setImageBitmap(bitmap);
            } catch (Exception e) {
            }

        }
}

private String getPath(Uri selectedImageUri) {

    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(selectedImageUri,
            projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}


回答4:

You will need to load the image from the SDCard to a Bitmap, and then set the bitmap image to the ImageView:

Bitmap bmp = BitmapFactory.decodeFile("/path/to/file.png");
iv_image.setImageBitmap(bmp);

As stated by yahya, you could also create a drawable out of the SDCard image file and then set the image drawable:

iv_image.setImageDrawable(Drawable.createFromPath("/path/to/file.png"));

You should also make sure that in your Manifest you include a permission to read (/write) to the SDCard.