这个问题已经有了答案:
How to pick an image from gallery (SD Card) for my app?
10答
我有一个带有默认图像的imageview
,我希望当用户单击imageview打开一个图像选择器,然后他从sdcard中选择自己的图像,然后图像就在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" />
爪哇
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;
}
最佳答案
我想这就是你要找的
if (Environment.getExternalStorageState().equals("mounted")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(
Intent.createChooser(
intent,
"Select Picture:"),
requestCode);
}
以及处理回拨
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);
}
希望有帮助
关于android - android从sdcard选择图片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14744854/