I am using camera 2 API for creating my own camera. I want to set the image taken by the camera in to an ImageView
, which is on another activity. I have tried this code but it is not working. When clicking the camera button the photo is saved to an sdcard location, but it is not showing on the ImageView
in the third Activity (which should receive the image and set it to an ImageView). I am passing the image as bitmap object via an Intent
. Can anyone help me?
Camera Activity
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();
}
}
Method 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);
}
}
}
}}
I think that you should pass the bitmap like this:
and then receive it as parcelable data like this in your third activity:
and then just set the bitmap to an
ImageView
Hopefully this helps you :) Write if you have any exceptions