Android选择图像或相机

时间:2016-07-27 20:11:33

标签: android android-camera android-imageview android-image android-gallery

我已经实现了从SD或相机中选择图像的代码。 但是,我的图片并未显示在ImageView中,我无法从SD卡中选择图片。

当我点击SD卡中的图像时,它会立即跳回我的活动。

    final String[] items = new String[] {"From Camera","From SD Card"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,items);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Select Image");
    builder.setAdapter(adapter,new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog,int which){
            if(which == 0){
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(),"event_image"+String.valueOf(System.currentTimeMillis()+".jpg"));
                imageCaptureUri = Uri.fromFile(file);
                try {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,imageCaptureUri);
                    intent.putExtra("return data",true);
                    startActivityForResult(intent,PICK_FROM_CAMERA);
                }catch(Exception ex){
                    ex.printStackTrace();
                }
                dialog.cancel();
            }else{
                intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Complete action using"),PICK_FROM_FILE);
            }
        }
    });
    final AlertDialog dialog = builder.create();
    mImageView  = (ImageView) findViewById(R.id.imageView);
    imagePicker = (ImageButton) findViewById(R.id.image_picker);
    imagePicker.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            dialog.show();
        }
    });

  @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode != RESULT_OK)
        return;
    Bitmap bitmap = null;
    String path ="";
    if(requestCode == PICK_FROM_FILE) {
        imageCaptureUri = data.getData();
        path = getRealPathFromURI(imageCaptureUri);
        if(path == null)
            path = imageCaptureUri.getPath();
        if(path != null){
            bitmap = BitmapFactory.decodeFile(path);
        }
    }else{
        path = imageCaptureUri.getPath();
        bitmap = BitmapFactory.decodeFile(path);
    }
    mImageView.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);
}

1 个答案:

答案 0 :(得分:0)

  1. 首先,你需要在AndroidManifest.xml中使用权限 WRITE_EXTERNAL_STORAGE

  2. 在xml布局中:

    <ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="380dp"
        android:background="#f241c9" />
    
    <Button
        android:id="@+id/btnCapture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="Take Photo" />
    
    <Button
        android:id="@+id/btnPick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="Pick Photo" />
    

  3. 在您的活动课程中:

    private static final String TAG = "my_log";
    private static final int REQUEST_CAPTURE_FROM_CAMERA = 1;
    private static final int REQUEST_PICK_FROM_FILE = 2;
    private static final int REQUEST_CROP_INTENT = 3;
    
    ImageView img;
    Button btnCapture, btnPick;
    File file;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        img = (ImageView) findViewById(R.id.img);
        btnCapture = (Button) findViewById(R.id.btnCapture);
        btnPick = (Button) findViewById(R.id.btnPick);
    
        btnCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_captured.jpg");
                // put Uri as extra in intent object
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent, REQUEST_CAPTURE_FROM_CAMERA);
            }
        });
    
        btnPick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), REQUEST_PICK_FROM_FILE);
            }
        });
    
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        if (resultCode != RESULT_OK) return;
    
        if (requestCode == REQUEST_CAPTURE_FROM_CAMERA) {
            try {
                cropImage(Uri.fromFile(file));
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        } else if (requestCode == REQUEST_PICK_FROM_FILE) {
            try {
                cropImage(data.getData());
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        } else if (requestCode == REQUEST_CROP_INTENT) {
            // Create an instance of bundle and get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap from extras
            Bitmap bitmap = extras.getParcelable("data");
            img.setImageBitmap(bitmap);
            if (saveBitmapToStorage(bitmap)) {
                Log.d(TAG, "Bitmap saved to file successful.");
            } else {
                Log.d(TAG, "Failed to save Bitmap to storage.");
            }
        }
    
    }
    
    public void cropImage(Uri picUri) {
        //call the standard crop action intent
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        //indicate image type and Uri of image
        cropIntent.setDataAndType(picUri, "image/*");
        //set crop properties
        cropIntent.putExtra("crop", "true");
        //indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        //indicate output X and Y
        cropIntent.putExtra("outputX", 256);
        cropIntent.putExtra("outputY", 256);
        //retrieve data on return
        cropIntent.putExtra("return-data", true);
        //start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, REQUEST_CROP_INTENT);
    }
    
    private boolean saveBitmapToStorage(Bitmap finalBitmap) {
        boolean result = false;
    
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_cropped.jpg");
        Log.d(TAG, "file path = " + file.getAbsolutePath());
    
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
    
            // send Broadcast to notify this photo and see it in Gallery
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(file);
            mediaScanIntent.setData(contentUri);
            sendBroadcast(mediaScanIntent);
    
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return result;
    }