如何从图库中拍照并在我的应用程序中使用此照片

时间:2012-07-23 09:05:02

标签: java android eclipse

我想从我的画廊拍照,我想给它一个“id”来使用我的Android应用程序。

2 个答案:

答案 0 :(得分:1)

按钮点击事件,请调用以下代码....

Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GET_IMAGE);

并且,在活动结果上,写下面的代码:

if (requestCode == GET_IMAGE) {    
  targetUri = data.getData();
  imageView.setImageURI(targetUri);                 
}

其中,private static final int GET_IMAGE = 2;

答案 1 :(得分:0)

您可以尝试以下代码

    btnChoosePhoto.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);

            startActivityForResult(i, 1);
        }
    });


public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == RESULT_OK && requestCode == 1 ) {

        final Uri selectedImage = data.getData();

        try {
            bitmap = Media.getBitmap(getContentResolver(),selectedImage);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

            //path = selectedImage.getEncodedPath();

            // create new file to write the encrypted bytes of image in file
            File f = new File(Environment.getExternalStorageDirectory()
                    + File.separator
                    + filename);
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        imageView.setImageBitmap(bitmap);

    }
}