Android 如何将相机拍摄的图像设置为ImageView?

Android 如何将相机拍摄的图像设置为ImageView?,android,android-camera,android-bitmap,Android,Android Camera,Android Bitmap,我正在使用camera 2 API创建自己的相机。我想将相机拍摄的图像设置为另一个活动中的ImageView。我尝试过这个代码,但它不起作用。单击相机按钮时,照片会保存到SD卡位置,但在第三个活动中,照片不会显示在ImageView上(该活动应接收图像并将其设置为ImageView)。我通过Intent将图像作为位图对象传递。有人能帮我吗 摄像机活动 public class SecondActivity extends Activity { ImageButton imagebutton;

我正在使用camera 2 API创建自己的相机。我想将相机拍摄的图像设置为另一个活动中的
ImageView
。我尝试过这个代码,但它不起作用。单击相机按钮时,照片会保存到SD卡位置,但在第三个活动中,照片不会显示在
ImageView
上(该活动应接收图像并将其设置为ImageView)。我通过
Intent
将图像作为位图对象传递。有人能帮我吗

摄像机活动

public class SecondActivity extends Activity {


ImageButton imagebutton;
private static int RESULT_LOAD_IMAGE = 1;
private final static String TAG = "Camera2testJ";
private Size mPreviewSize;
private static final int CAMERA_REQUEST = 1888;
private TextureView mTextureView;
private CameraDevice mCameraDevice;
private CaptureRequest.Builder mPreviewBuilder;
private CameraCaptureSession mPreviewSession;

private Button cancelbtn;
private ImageButton mBtnShot;
public  String picturePath;
public Bitmap photo;
int flag=1;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();

static {
    ORIENTATIONS.append(Surface.ROTATION_0, 90);
    ORIENTATIONS.append(Surface.ROTATION_90, 0);
    ORIENTATIONS.append(Surface.ROTATION_180, 270);
    ORIENTATIONS.append(Surface.ROTATION_270, 180);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_second);
    loadPic();
    mTextureView = (TextureView)findViewById(R.id.texture);
    mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);

    mBtnShot = (ImageButton)findViewById(R.id.btn_takepicture);
    mBtnShot.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.e(TAG, "mBtnShot clicked");
            takePicture();
            //sendImage(flag=0);
        }

    });

    imagebutton=(ImageButton)findViewById(R.id.buttonLoadPicture2);
    imagebutton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);



        }

    });

    cancelbtn=(Button)findViewById(R.id.buttonLoadPicture3);
    cancelbtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {


            finish();

        }

    });

}

protected void takePicture() {
    Log.e(TAG, "takePicture");
    if(null == mCameraDevice) {
        Log.e(TAG, "mCameraDevice is null, return");
        return;
    }

    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());

        Size[] jpegSizes = null;
        if (characteristics != null) {
            jpegSizes = characteristics
                    .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
                    .getOutputSizes(ImageFormat.JPEG);
        }
        int width = 640;
        int height = 480;
        if (jpegSizes != null && 0 < jpegSizes.length) {
            width = jpegSizes[0].getWidth();
            height = jpegSizes[0].getHeight();
        }

        ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
        List<Surface> outputSurfaces = new ArrayList<Surface>(2);
        outputSurfaces.add(reader.getSurface());
        outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture()));

        final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(reader.getSurface());
        captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);

        // Orientation
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));

        final File file = new File(Environment.getExternalStorageDirectory()+"/DCIM", "pic.jpg");

        ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {

            @Override
            public void onImageAvailable(ImageReader reader) {

                Image image = null;
                try {
                    image = reader.acquireLatestImage();
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.get(bytes);
                    save(bytes);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }

            private void save(byte[] bytes) throws IOException {
                OutputStream output = null;
                try {
                    output = new FileOutputStream(file);
                    output.write(bytes);
                } finally {
                    if (null != output) {
                        output.close();
                    }
                }
            }

        };

        HandlerThread thread = new HandlerThread("CameraPicture");
        thread.start();
        final Handler backgroudHandler = new Handler(thread.getLooper());
        reader.setOnImageAvailableListener(readerListener, backgroudHandler);

        final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {

            @Override
            public void onCaptureCompleted(CameraCaptureSession session,
                                           CaptureRequest request, TotalCaptureResult result) {

                super.onCaptureCompleted(session, request, result);
                Toast.makeText(SecondActivity.this, "Saved:"+file, Toast.LENGTH_SHORT).show();



                ////////////sending image

               /* flag=flag-1;
                sendImage(flag);*/
              // startPreview();
             /////sending image

            }

        };

        mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {

            @Override
            public void onConfigured(CameraCaptureSession session) {

                try {
                    session.capture(captureBuilder.build(), captureListener, backgroudHandler);
                } catch (CameraAccessException e) {

                    e.printStackTrace();
                }

            }


            @Override
            public void onConfigureFailed(CameraCaptureSession session) {

            }
        }, backgroudHandler);

    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

}

@Override
protected void onResume() {
    super.onResume();
    Log.e(TAG, "onResume");
}

private void openCamera() {

    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    Log.e(TAG, "openCamera E");
    try {
        String cameraId = manager.getCameraIdList()[0];
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        mPreviewSize = map.getOutputSizes(SurfaceTexture.class)[0];

        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
    Log.e(TAG, "openCamera X");
}

private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener(){

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        Log.e(TAG, "onSurfaceTextureAvailable, width="+width+",height="+height);
        openCamera();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface,
                                            int width, int height) {
        Log.e(TAG, "onSurfaceTextureSizeChanged");
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        //Log.e(TAG, "onSurfaceTextureUpdated");
    }

};

private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

    @Override
    public void onOpened(CameraDevice camera) {

        Log.e(TAG, "onOpened");
        mCameraDevice = camera;
        startPreview();
    }

    @Override
    public void onDisconnected(CameraDevice camera) {

        Log.e(TAG, "onDisconnected");
    }

    @Override
    public void onError(CameraDevice camera, int error) {

        Log.e(TAG, "onError");
    }

};

@Override
protected void onPause() {

    Log.e(TAG, "onPause");
    super.onPause();
    if (null != mCameraDevice) {
        mCameraDevice.close();
        mCameraDevice = null;
    }
}

protected void startPreview() {

    if(null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
        Log.e(TAG, "startPreview fail, return");
        return;
    }

    SurfaceTexture texture = mTextureView.getSurfaceTexture();
    if(null == texture) {
        Log.e(TAG,"texture is null, return");
        return;
    }

    texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface surface = new Surface(texture);

    try {
        mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
    } catch (CameraAccessException e) {

        e.printStackTrace();
    }
    mPreviewBuilder.addTarget(surface);

    try {
        mCameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {

            @Override
            public void onConfigured(CameraCaptureSession session) {

                mPreviewSession = session;
                updatePreview();
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session) {

                Toast.makeText(SecondActivity.this, "onConfigureFailed", Toast.LENGTH_LONG).show();
            }
        }, null);
    } catch (CameraAccessException e) {

        e.printStackTrace();
    }

}

protected void updatePreview() {

    if(null == mCameraDevice) {
        Log.e(TAG, "updatePreview error, return");
    }

    mPreviewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    HandlerThread thread = new HandlerThread("CameraPreview");
    thread.start();
    Handler backgroundHandler = new Handler(thread.getLooper());

    try {
        mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, backgroundHandler);
    } catch (CameraAccessException e) {

        e.printStackTrace();

    }

}

在课堂部分添加这一行

final int TAKE_PHOTO_REQ = 100;


  ImageView imageView;
在调用方法中添加这两行

  imageView = (ImageView)findViewById(R.id.iv);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PHOTO_REQ);
加上这个

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case TAKE_PHOTO_REQU: {
            if (resultCode == TakePicture.RESULT_OK && data != null) {

                Bitmap myBmp = (Bitmap) data.getExtras().get("data");

                imageView.setImageBitmap(myBmp);
            }
        }
       }
      }

希望这会有帮助。谢谢。我想你应该像这样传递位图:

Intent intent = new Intent(this, ThirdActivity.class);
intent.putExtra("BitmapImage", photo);
然后在您的第三个活动中将其作为包裹数据接收:

Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
然后将位图设置为
ImageView

imageView.setImageBitmap(bitmap);

希望这能帮助您:)如果您有任何异常,请编写代码

这是我的xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/linear">
<Button android:id="@+id/btn" android:layout_width="200dp"
    android:layout_height="wrap_content" android:text="Click" />
<ImageView android:id="@+id/img_preview"
    android:layout_width="fill_parent" android:layout_height="fill_parent"/>
</LinearLayout>
这是onActivityResult

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        cursor.close();
        flag=flag+1;
       /* ImageView imageView = (ImageView) findViewById(R.id.imgView2);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));*/
       sendImage(flag);

    }
  if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        photo = (Bitmap) extras.get("data");

      flag=flag-1;
      sendImage(flag);


      /*  photo = (Bitmap) data.getExtras().get("data");*/
       // imageView.setImageBitmap(photo);




   }

}
   public void sendImage(int flag)
   {
      // id=flag;
       if(flag==2) {
           Intent myIntent1 = new Intent(SecondActivity.this, ThirdActivity.class);
           myIntent1.putExtra("key", picturePath);
           // myIntent1.putExtra("key2",
           SecondActivity.this.startActivity(myIntent1);
       }
       if(flag==0)
       {
           Intent myIntent1 = new Intent(SecondActivity.this, ThirdActivity.class);
           myIntent1.putExtra("key", photo);
           // myIntent1.putExtra("key2",
           SecondActivity.this.startActivity(myIntent1);
       }
   }
void loadPic()
{
    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    String pathName = baseDir + "/DCIM/camera/";
    File parentDir=new File(pathName);

    File[] files = parentDir.listFiles();
    Date lastDate = null;
    String lastFileName;
    boolean isFirstFile = true; //just temp variable for being sure that we are on the first file
    for (File file : files) {
        if(isFirstFile){
            lastDate = new Date(file.lastModified());
            isFirstFile = false;
        }
        if(file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")){
            Date lastModDate = new Date(file.lastModified());
            if (lastModDate.after(lastDate))  {
                lastDate = lastModDate;
                lastFileName = file.getName();

                //  String baseDir2 = Environment.getExternalStorageDirectory().getAbsolutePath();
                //String fileName = lastFileName;
                String pathName2 = pathName +lastFileName;//maybe your folders are /DCIM/camera/

                Bitmap bmp = BitmapFactory.decodeFile(pathName2);
                ImageButton button1 = (ImageButton)findViewById(R.id.buttonLoadPicture2);
                button1.setImageBitmap(bmp);
            }
        }
    }
}}
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
     switch(requestCode){
     case CAMERA_PIC_REQUEST:
          if(resultCode==RESULT_OK){
              Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            imgView.setImageBitmap(thumbnail);
        }
   }
 }
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
     switch(requestCode){
     case CAMERA_PIC_REQUEST:
          if(resultCode==RESULT_OK){
              Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            imgView.setImageBitmap(thumbnail);
        }
   }
 }