从SD卡浏览图像以在android中的图像视图中显示它?

时间:2013-11-28 11:00:00

标签: android android-dialog

我使用活动作为对话框。我有按钮浏览并选择图像以在图像视图中显示它。

我的对话活动代码和浏览图片

public class Update_profile extends Activity{

private Uri mImageCaptureUri;

private static final int PICK_FROM_FILE = 1;

private View rootView;
Button save,browse_image;
ImageView profile_pic;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setBackgroundDrawable(new ColorDrawable(0));
    setContentView(R.layout.update_profile);

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }
    });

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    this.rootView=findViewById(R.id.update_profile_details);
    profile_pic = (ImageView)findViewById(R.id.update_profile_picture);

    save = (Button)findViewById(R.id.save);
    browse_image = (Button)findViewById(R.id.browse_image);
    browse_image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent intent = new Intent();

            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);

            startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);

        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) return;

    Bitmap bitmap   = null;
    String path     = "";

    if (requestCode == PICK_FROM_FILE) {
        mImageCaptureUri = data.getData(); 
        path = getRealPathFromURI(mImageCaptureUri); //from Gallery
        Log.v("Path", ""+path);

        if (path == null)
            path = mImageCaptureUri.getPath(); //from File Manager
        Log.v("Path", ""+path);

        if (path != null) 
            bitmap  = BitmapFactory.decodeFile(path);
    } else {
        path    = mImageCaptureUri.getPath();
        Log.v("Path", ""+path);
        bitmap  = BitmapFactory.decodeFile(path);
    }

    profile_pic.setImageBitmap(bitmap);     
}

public String getRealPathFromURI(Uri contentUri) {
    String [] proj      = {MediaStore.Images.Media.DATA};
    Cursor cursor       = managedQuery( contentUri, proj, null, null,null);

    if (cursor == null) return null;

    int column_index    = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

    cursor.moveToFirst();

    return cursor.getString(column_index);
}

@SuppressLint("NewApi")
@Override
public boolean onTouchEvent(MotionEvent event) {
   Rect rect = new Rect();
   rootView.getHitRect(rect);
   if (!rect.contains((int)event.getX(), (int)event.getY())){
       setFinishOnTouchOutside(false); 
          return true;
   }
      return false;       
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {

        finish();
    }
    return true;
}
}

我的清单代码将活动更改为对话框

<activity
        android:name="test.Update_profile"
        android:excludeFromRecents="true"
        android:launchMode="singleInstance"
        android:screenOrientation="portrait"
        android:theme="@android:style/Theme.Dialog"
        android:windowSoftInputMode="stateHidden" >
</activity>

当使用上面的浏览图像时,普通活动中的代码意味着它会获取图像并在图像视图中显示但在此对话框活动中。现在可以选择图像。我想从对话框活动中拍摄图像。能够解决这个问题。任何人都知道请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

You can try this : 

    public class EMView extends Activity {
    ImageView img,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);
        img= (ImageView)findViewById(R.id.gimg1);



    ((Button) findViewById(R.id.Button01))
    .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);


        }
    });
}

//UPDATED
@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);

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

}

答案 1 :(得分:1)

如果您想直接从gallary中检索,请使用此代码 http://viralpatel.net/blogs/pick-image-from-galary-android-app/

这是我从sdcard获取所有文件的方法,你只需将它保存在一个datacontroller类中哦ohd dude

private void getallimages()
            {
                String[] STAR = { "*" };


                final String[] columns = { MediaStore.Images.Thumbnails._ID , MediaStore.Images.Media.DATA};
                final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
                Cursor imagecursor = ((Activity) cntx).managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
                int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
                int imgNameIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
                int count = imagecursor.getCount();
                for (int i = 0; i < count; i++) {
                    imagecursor.moveToPosition(i);
                    int id = imagecursor.getInt(image_column_index);
                    ImageItem imageItem = new ImageItem();
                    imageItem.id = id;
                    imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    lastId = id;
                    imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(cntx.getContentResolver(), id,MediaStore.Images.Thumbnails.MICRO_KIND, null);
                    imageItem.selection = false; //newly added item will be selected by default
                    controller.images.add(imageItem);
                }

            }

这是ImageItem包装类

 public class ImageItem {
            public boolean selection=true;
            public int id;
            public Bitmap img;
            public String filePath;
            public String fileType;
    }