android 从 sdcard 选择图像

标签 android android-intent android-imageview

<分区>

我有一个带有默认图像的 imageview,我希望当用户单击 imageview 打开图像选择器然后他从 sdcard 选择他的图像然后图像在 imageview 上,

这是我的图片 View

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

最佳答案

我想这就是你要找的

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 从 sdcard 选择图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14744854/

相关文章:

android - 如何在没有硬件加速的情况下在 Windows 8 上为 API 21 和 19 运行适用于 Intel x86 Atom 的 Android 模拟器?

java - 在 Kotlin 中将 Dp 转换为 Px - 这种转换永远不会成功

android - 一段时间后 Connectify 停止互联网连接

java - 如何将数据从非 Activity 类传递到android中的 Activity ?

android - 在 Android 中从 SD 卡打开 Photoshpere 以在 Google Cardboard 中查看

javascript - 向 Android 设备发送通知。已发送但未收到

android - 异步任务 : onPostExecute is not being invoked

android - 将多维字符串数组传递给 Android 中的新 Activity

android - 如何在不降低质量的情况下在任何屏幕上适应 png/jpg 图像?

android - 在 Android 中,我可以在布局 xml 中使用 Assets 中的图像吗?