Android从SD卡选择图像 [英] android select image from sdcard

查看:101
本文介绍了Android从SD卡选择图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有默认图像的imageview,我希望当用户单击图像视图以打开图像选择器,然后他从sdcard中选择其图像,然后该图像位于图像视图中,

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,

这是我的图像视图

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

推荐答案

我认为这就是您要寻找的

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

并处理回调

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从SD卡选择图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆