Out of memory Error when previewing image in android - android

I have a custom camera application. When capture a image the application crashes. It should look like when capture then the image will preview on the screen but it crashes(Out of memory error). There are two activity (one is CustomCamera activity with two buttons and Preview activity with two buttons).
Here is my CustomCameraActivity:
public class CustomCameraActivity extends Activity implements
SurfaceHolder.Callback {
#Override
public 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.main);
context = this;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mOrientaion1 = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
imageView = (ImageView) findViewById(R.id.imgError);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
Button btn1 = (Button) viewControl.findViewById(R.id.Button01);
Button btn2 = (Button) viewControl.findViewById(R.id.Button02);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Toast.makeText(context, "1111111111111111111111111",
// Toast.LENGTH_SHORT).show();
camera.takePicture(null, null, mPicture);
Constant.rotationValueForCamera = Constant.rotationValue;
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Toast.makeText(context, "22222222222222222222222222",
// Toast.LENGTH_SHORT).show();
Log.e("0 imagePickerStatus", Constant.imagePickerStatus + "");
Constant.imagePickerStatus = 0;
Log.e("0 imagePickerStatus", Constant.imagePickerStatus + "");
finish();
}
});
this.addContentView(viewControl, layoutParamsControl);
int ot = getResources().getConfiguration().orientation;
if (Configuration.ORIENTATION_LANDSCAPE == ot) {
imageView.setVisibility(View.GONE);
Log.e("ori1111", "land");
} else {
imageView.setVisibility(View.VISIBLE);
Log.e("ori111", "port");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
findViewById(R.id.Button01).setVisibility(View.VISIBLE);
findViewById(R.id.Button02).setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
Log.e("ori", "land");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
// Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
findViewById(R.id.Button01).setVisibility(View.INVISIBLE);
findViewById(R.id.Button02).setVisibility(View.INVISIBLE);
imageView.setVisibility(View.VISIBLE);
Log.e("ori", "port");
}
}
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener);
}
#Override
public void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
if (Constant.isCapturedOk) {
Constant.isCapturedOk = false;
finish();
}
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.e("Camrera", "22222222222222222");
Intent intent = new Intent(context, PreviewActivity.class);
// intent.putExtra("data", data);
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
data.length);
Matrix matrix = new Matrix();
if (Constant.result == 180) {
matrix.postRotate(270);
}
if (Constant.result == 270) {
matrix.postRotate(180);
}
int height = bitmapPicture.getHeight();
int width = bitmapPicture.getWidth();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapPicture,
height, width, true);
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
rotatedBitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, blob);
byte[] bitmapdata = blob.toByteArray();
Constant.imageData = bitmapdata;
startActivity(intent);
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
setCameraDisplayOrientation(this,cameraId,camera);
previewing = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
Constant.result = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
Constant.result = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
Constant.result = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
Constant.result = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
#Override
protected void onStop() {
super.onStop();
Log.e("Tab", "Stoping");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Here is my Preview Activity:
public class PreviewActivity extends Activity {
Context context;
Button btnRetake, btnOk;
// byte[] data;
ImageView imgPreview;
#Override
public 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.preview_layout);
context = this;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
btnRetake = (Button) findViewById(R.id.btn1FromPreviw);
btnOk = (Button) findViewById(R.id.btn2FromPreviw);
imgPreview = (ImageView) findViewById(R.id.imgImagePreview);
// Intent myIntent = getIntent();
// data = myIntent.getExtras().getByteArray("data");
Drawable image = null;
image = new BitmapDrawable(BitmapFactory.decodeByteArray(
Constant.imageData, 0, Constant.imageData.length));
imgPreview.setBackgroundDrawable(image);
// image = new BitmapDrawable(Constant.imageData);
// imgPreview.setBackgroundDrawable(image);
btnRetake.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Constant.isCapturedOk = false;
finish();
}
});
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SaveImage();
}
});
}
private void SaveImage() {
/*
* File pictureFile = getOutputMediaFile(); if (pictureFile == null) {
* Log.e("Camrera", "nullllllllllllllllll"); return; }
*/
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(Constant.imageData , 0, Constant.imageData.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG ,50 , stream);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Android" + File.separator + "data"
+ File.separator + context.getPackageName()
+ File.separator + "files" + File.separator + "image.jpg");
Log.e("pa", file.getPath() + " : " + file.getAbsolutePath());
Log.e("len", stream.size() + "");
file.createNewFile();
/*
* Log.e("Camrera", "yesssssssssssssssssss"); Log.e("Camrera",
* pictureFile.getAbsolutePath());
*/
FileOutputStream fos = new FileOutputStream(file);
fos.write(stream.toByteArray());
fos.close();
Log.e("Camrera", "great");
Constant.isCapturedOk = true;
Log.e("1 imagePickerStatus", Constant.imagePickerStatus + "");
Constant.imagePickerStatus = 1;
Log.e("1 imagePickerStatus", Constant.imagePickerStatus + "");
finish();
} catch (FileNotFoundException e) {
Log.e("mPicture FileNotFoundException", e.toString());
} catch (IOException e) {
Log.e("mPicture IOException", e.toString());
}
}
private File getOutputMediaFile() {
File mediaFile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Android" + File.separator + "data"
+ File.separator + context.getPackageName() + File.separator
+ "files" + File.separator + "image.jpg");
return mediaFile;
}
#Override
protected void onStop() {
super.onStop();
Log.e("Tab", "Stoping");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Help me.

Can have a look on this
http://developer.android.com/training/displaying-bitmaps/index.html
Strange out of memory issue while loading an image to a Bitmap object
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options);

Related

Camera is skewed and rotated

Its the first time i have used surface view and surface holder with a very rough knowledge of both, the live image preview in the surfaceview is skewed and rotated, on searching i found out i need to set CameraParameter but i could understand how it works and also is there any guide to understanding the Camera2 api
public class CamActivity extends AppCompatActivity implements SurfaceHolder.Callback{
Camera mCamera;
SurfaceView surfaceView;
private SurfaceHolder mHolder;
FloatingActionButton cam;
private static final int pRequestCode = 5002;
private static final String[] mPermissions = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cam_layout);
checkCameraHardware();
checkPermissions();
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
surfaceView = (SurfaceView) findViewById(R.id.camera_preview);
mHolder = surfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cam = (FloatingActionButton) findViewById(R.id.fabCamera);
cam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
}
);
}
private boolean checkCameraHardware() {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
private void checkPermissions() {
if (ContextCompat.checkSelfPermission(this, mPermissions[0]) != PackageManager.PERMISSION_GRANTED
||ContextCompat.checkSelfPermission(this, mPermissions[1]) != PackageManager.PERMISSION_GRANTED
||ContextCompat.checkSelfPermission(this, mPermissions[2]) != PackageManager.PERMISSION_GRANTED
||ContextCompat.checkSelfPermission(this, mPermissions[3]) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, mPermissions, pRequestCode);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case pRequestCode: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"Camera Allowed",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Camera Denied",Toast.LENGTH_SHORT).show();
}
if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"Location Allowed",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Location Denied",Toast.LENGTH_SHORT).show();
}
if (grantResults.length > 0 && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"Microphone Allowed",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Microphone Denied",Toast.LENGTH_SHORT).show();
}
if (grantResults.length > 0 && grantResults[3] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"Storage Allowed",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Storage Denied",Toast.LENGTH_SHORT).show();
}
return;
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera = Camera.open();
}
catch (Exception e){
}
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("orientation", "portrait");
mCamera.setParameters(parameters);
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
try {
mCamera.stopPreview();
} catch (Exception e){
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d("", "Error creating media file, check storage permissions: " );
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("", "Error accessing file: " + e.getMessage());
}
}
};
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
For Camera2 API you can check Android code sample from Android Studio or GitHub.
You can solve camera preview rotation and aspect ratio in surfaceCreated() like this. Note that you'll have to properly deal with the exceptions:
#Override
public void surfaceCreated(SurfaceHolder holder) {
// You need to open the camera in a
// different manner so you can obtain some info from it
int numberOfCameras = Camera.getNumberOfCameras();
Camera.CameraInfo info = new Camera.CameraInfo();
mCamera = null;
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, info);
// Open a back camera
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
try {
mCamera = Camera.open(i);
break;
} catch (RuntimeException e) {
// Could not open camera
}
}
}
if (mCamera == null) {
// No camera found
}
Camera.Parameters parameters = mCamera.getParameters();
// Rotate display
// Code from here:
// https://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int)
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
mCamera.setDisplayOrientation(result);
Camera.Size size = parameters.getPreviewSize();
// You'll probably want to set the preview
// width and height to match the preview size
// aspect ratio that you can obtain by:
// (double) size.width / (double) size.height
//
// Note that if the int result above modulo 180
// equals 90, you'll have to exchange width for height
// and vice versa.
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}

Android Application : display image

i'm working on a android application and I have to take a picture and save it. It's working and my picture is saved in a directory of the phone. Especially, in Picture directory.
So, here its my class parameter with the button to launch the camera ( new activity) and take the picture :
public class Parametre extends Activity {
private EditText ETpseudo= null;
private Button buttonPhoto = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parametres);
ETpseudo =(EditText) findViewById(R.id.editPseudo);
buttonPhoto = (Button) findViewById(R.id.buttonPhoto);
//ivPhoto.setImageBitmap();
buttonPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Parametre.this, CameraActivity.class));
}
});
}
}
CameraActivity :
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
private ImageView cadrePhoto = null;
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
Log.d("DEBUG", String.valueOf(grantResults[0]));
startCamera();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
Button captureButton = (Button) findViewById(R.id.button_capture);
startCamera();
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
private void startCamera(){
mCamera = getCameraInstance();
mCamera.startPreview();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
setCameraDisplayOrientation(this, 1, mCamera);
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open(1);
} catch (Exception e) {
e.printStackTrace();
}
return camera;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void setCameraDisplayOrientation(Activity activity, int cameraId,android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("Error", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("DBG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Error", "Error accessing file: " + e.getMessage());
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
So, after taking the photo, I want to display the image on an ImageView in the parameter view. But I dont know how to do this. How to get back the photo and display him on the parameter View ?
Thanks.
Sorry for my english :/
you can do this in as easy way just create an static bitmap when picture taken in picturecallback method
Bitmap bmap=BitmapFactory.decodeByteArray(data, 0, data.length,sizeOptions);
Log.e("clickedbitmaaapp", String.valueOf(bmap));
static Bitmap mBitmap=bmap;
create this bitmap in other class which where you can access this easily.
Thanks you.
I can't test my code now. But do you think that should work here ? :
(cameraActivity)
public class CameraActivity extends Activity {
static Bitmap mBitmap;
...
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("Error", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bmap= BitmapFactory.decodeByteArray(data, 0, data.length, options);
mBitmap = bmap;
} catch (FileNotFoundException e) {
Log.d("DBG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Error", "Error accessing file: " + e.getMessage());
}
}
};
and then in my parameter class :
public class Parametre extends Activity {
private EditText ETpseudo= null;
private Button buttonPhoto = null;
private ImageView iv = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parametres);
ETpseudo =(EditText) findViewById(R.id.editPseudo);
buttonPhoto = (Button) findViewById(R.id.buttonPhoto);
//ivPhoto.setImageBitmap();
buttonPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Parametre.this, CameraActivity.class));
}
});
ImageView imageView=(ImageView)findViewById(R.id.cadreImage);
imageView.setImageBitmap(CameraActivity.mBitmap);
}
}

Show captured image in ImageView fails with back camera

I developed an app in which the user can capture an image either from camera or gallery. For that, the user can click on the imageview, then a dialog shows up and the user can choose to capture from camera or gallery.
If the user chooses to capture the image from gallery or with the front camera then it works fine and the captured image shows up in the imageview. But if the user chooses the back camera and takes the photo and return back to activity, then the image does not show up in the imageview at all.
Here my full source code:
public class PostActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.post);
image = (ImageView) findViewById(R.id.image);
ab = getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
show(); //here the dialog box is called, to choose the capture option
}
});
image.setTag(null);
captureImageInitialization();
}
private void show() {
dialog.show();
}
private void captureImageInitialization() {
final Item[] items = {
new Item("Camera", R.drawable.ic_action_camera_dark),
new Item("Gallery", R.drawable.ic_action_collection),
};
ListAdapter adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1, items) {
public View getView(int position, View convertView, ViewGroup parent) {
// User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(android.R.id.text1);
// Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(
items[position].icon, 0, 0, 0);
// Add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp5);
return v;
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Take Image from ...");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
public static class Item {
public final String text;
public final int icon;
public Item(String text, Integer icon) {
this.text = text;
this.icon = icon;
}
#Override
public String toString() {
return text;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
BitmapFactory.Options options0 = new BitmapFactory.Options();
options0.inSampleSize = 2;
options0.inScaled = false;
options0.inDither = false;
options0.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagepath, options0);
Matrix matrix = new Matrix();
ExifInterface exif;
int m = 0;
try {
exif = new ExifInterface(imagepath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
Log.d("EXIF", "Exif: " + orientation);
if (orientation == 6) {
m = 90;
} else if (orientation == 3) {
m = 180;
} else if (orientation == 8) {
m = 270;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
matrix.postRotate(m);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), matrix, false);
ByteArrayOutputStream baos0 = new ByteArrayOutputStream();
image.setImageBitmap(getRoundedCornerBitmap(bmp));
image.setTag("1");
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos0);
byte[] imageBytes0 = baos0.toByteArray();
krt1 = Base64.encodeToString(imageBytes0, Base64.DEFAULT);
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inScaled = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagepath, options);
ExifInterface exif2;
int m2 = 0;
try {
exif2 = new ExifInterface(imagepath);
int orientation = exif2.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
Log.d("EXIF", "Exif: " + orientation);
if (orientation == 6) {
m2 = 90;
} else if (orientation == 3) {
m2 = 180;
} else if (orientation == 8) {
m2 = 270;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
Matrix matrix2 = new Matrix();
matrix2.postRotate(m2);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), matrix2, false);
image.setImageBitmap(getRoundedCornerBitmap(bmp));
image.setTag("1");
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
krt1 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
break;
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver().query(uri,
proj, null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
This issue with the back camera is really weird, because I never had such an issue. (BTW tested on Samsung device). Any help is appreciated.
I am using this code for taking the image from front facing camera -
public class CameraController {
private Context context;
private boolean hasCamera;
private Camera camera;
private int cameraId;
public CameraController(Context c){
context = c.getApplicationContext();
if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
cameraId = getFrontCameraId();
if(cameraId != -1){
hasCamera = true;
}else{
hasCamera = false;
}
}else{
hasCamera = false;
}
}
public boolean hasCamera(){
return hasCamera;
}
public void getCameraInstance(){
camera = null;
if(hasCamera){
try{
camera = Camera.open(cameraId);
prepareCamera();
}
catch(Exception e){
hasCamera = false;
}
}
}
public void takePicture(){
if(hasCamera){
camera.takePicture(null,null,mPicture);
}
}
public void releaseCamera(){
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
}
private int getFrontCameraId(){
int camId = -1;
int numberOfCameras = Camera.getNumberOfCameras();
CameraInfo ci = new CameraInfo();
for(int i = 0;i < numberOfCameras;i++){
Camera.getCameraInfo(i,ci);
if(ci.facing == CameraInfo.CAMERA_FACING_FRONT){
camId = i;
}
}
return camId;
}
private void prepareCamera(){
SurfaceView view = new SurfaceView(context);
try{
camera.setPreviewDisplay(view.getHolder());
}catch(IOException e){
throw new RuntimeException(e);
}
camera.startPreview();
Camera.Parameters params = camera.getParameters();
params.setJpegQuality(100);
camera.setParameters(params);
}
private PictureCallback mPicture = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera){
File pictureFile = getOutputMediaFile();
if(pictureFile == null){
Log.d("TEST", "Error creating media file, check storage permissions");
return;
}
try{
Log.d("TEST","File created");
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
}catch(FileNotFoundException e){
Log.d("TEST","File not found: "+e.getMessage());
} catch (IOException e){
Log.d("TEST","Error accessing file: "+e.getMessage());
}
}
};
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if(!mediaStorageDir.exists()){
if(!mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg");
return mediaFile;
}
}
Hope this helps you.

Android camera saving images with wrong orientation

I have a camera app that uses only the portrait mode (restricted via android manifest file). Following code is my SurfaceView used for the Camera
public class CameraPreview extends SurfaceView implements SensorEventListener, SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
private Activity mActivity;
private static boolean DEBUGGING = true;
private static final String LOG_TAG = "CameraPreviewSample";
private static final String CAMERA_PARAM_ORIENTATION = "orientation";
private static final String CAMERA_PARAM_LANDSCAPE = "landscape";
private static final String CAMERA_PARAM_PORTRAIT = "portrait";
protected List<Camera.Size> mPreviewSizeList;
protected List<Camera.Size> mPictureSizeList;
protected Camera.Size mPreviewSize;
protected Camera.Size mPictureSize;
// Constructor that obtains context and camera
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
mActivity=(Activity)context;
mCamera = camera;
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
if (mSurfaceHolder.getSurface() == null) {
// preview surface does not exist
return;
}
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
try {
Camera.Parameters cameraParams = mCamera.getParameters();
boolean portrait = isPortrait();
configureCameraParameters(cameraParams, portrait);
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d("CameraView", "Error starting camera preview: " + e.getMessage());
}
}
protected void configureCameraParameters(Camera.Parameters cameraParams, boolean portrait) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { // for 2.1 and before
if (portrait) {
cameraParams.set(CAMERA_PARAM_ORIENTATION, CAMERA_PARAM_PORTRAIT);
} else {
cameraParams.set(CAMERA_PARAM_ORIENTATION, CAMERA_PARAM_LANDSCAPE);
}
} else { // for 2.2 and later
int angle;
Display display = mActivity.getWindowManager().getDefaultDisplay();
switch (display.getRotation()) {
case Surface.ROTATION_0: // This is display orientation
angle = 90; // This is camera orientation
break;
case Surface.ROTATION_90:
angle = 0;
break;
case Surface.ROTATION_180:
angle = 270;
break;
case Surface.ROTATION_270:
angle = 180;
break;
default:
angle = 90;
break;
}
Log.v(LOG_TAG, "angle: " + angle);
mCamera.setDisplayOrientation(angle);
}
cameraParams.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
cameraParams.setPictureSize(mPictureSize.width, mPictureSize.height);
if (DEBUGGING) {
Log.v(LOG_TAG, "Preview Actual Size - w: " + mPreviewSize.width + ", h: " + mPreviewSize.height);
Log.v(LOG_TAG, "Picture Actual Size - w: " + mPictureSize.width + ", h: " + mPictureSize.height);
}
mCamera.setParameters(cameraParams);
}
public boolean isPortrait() {
return (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent arg0) {
// TODO Auto-generated method stub
}
}
When the application saves an an images (taken in portrait mode) It will be saved upside down. But in landscape mode it saves the image correctly. And as I have mentioned, the app has restricted the orientation to portrait mode only.
Also I tried to change EXIF within the Activity (Actually I am using a Fragment) data of the image file once it been saved, and then recreate the bitmap with new exif data using the following code, but still no success
private Bitmap changeExifData(String imagePath){
Bitmap correctBmp = null;
try {
File f = new File(imagePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
correctBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
}
catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
}
catch(OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
}
return correctBmp;
}
Your help is greatly appreciated.
Here is how I solved it (full implementation that includes saving the image). Image taken in in portrait mode will be rotated 90 degrees.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageTakeAndShow extends Activity {
private static final int ACTION_TAKE_PHOTO = 1;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
//private ImageView mImageView;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
TelephonyManager myPhonenumber;
static String device_id;
double latitude ,longitude;
Button Btn;
File f;
//save picture
private File getAlbumDir() {
File file = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
file = Environment.getExternalStorageDirectory().getAbsoluteFile();
file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Snap/Capture_Image");
Log.e("file", file.toString());
if (file != null) {
if (! file.mkdirs()) {
if (! file.exists()){
Log.d("Camera", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return file;
}
//create file name
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
//set picture width and height and rotate 90 degrees
private void setPic() {
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth/2;
int photoH = bmOptions.outHeight/2;
Log.e("photoW", Integer.valueOf(photoW).toString());
Log.e("photoH", Integer.valueOf(photoH).toString());
int scaleFactor = 1;
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
try{
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
bitmap = Bitmap.createScaledBitmap(bitmap, 800, 600, true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(mCurrentPhotoPath.toString());
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, 800,640,matrix, true);
FileOutputStream fos2 = new FileOutputStream(mCurrentPhotoPath.toString());
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos2);
fos2.close();
}catch (Exception e) {
e.printStackTrace();
}catch (OutOfMemoryError o) {
o.printStackTrace();
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
Log.e("path f", f.toString());
}
//Camera activity
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
}
startActivityForResult(takePictureIntent, actionCode);
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPhonenumber = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
device_id = myPhonenumber.getDeviceId();
mImageBitmap = null;
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
handleBigCameraPhoto();
final Intent intent = new Intent(getApplicationContext(), Image_Priview.class);
intent.putExtra("image parth", f.toString());
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
new Handler().postDelayed(new Runnable() {
public void run() {
}
}, 1000);
}else if (resultCode == RESULT_CANCELED){
File file = new File(mCurrentPhotoPath);
file.delete();
finish();
}
break;
}
}
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}

How to send multiple images to another activity in android?

In my application i have created a custom camera where it captures images and save it in sd card. And also can view it in second activity. But it just replaces the previous images which i dont want. How to send multiple images to second activity?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surfaceview);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
click = (Button) findViewById(R.id.button_capture);
click.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
filepath = Environment.getExternalStorageDirectory()+"/testing/"+"test.3gp";
System.out.println("thumbnail path~~~~~~"+filepath);
File file = new File(filepath);
Uri uriTarget = Uri.fromFile(file);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(CustomCameraActivity.this, "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",filepath.toString());
setResult(1,returnIntent);
finish();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// camera.startPreview();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
Just Convert your image into bitmap and pass that Bitmap in another activity by yourIntent.putExra("key",bitmap);
Or Use this:
private File imageFile;
private Uri imageUri;
private static final int CAMERA_REQUEST_CODE = 100;
private String imagePath
private Uri getTempUri() {
// Create an image file name
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String dt = sdf.format(new Date());
imageFile = null;
imageFile = new File(Environment.getExternalStorageDirectory()
+ "/foldername/", "Camera_" + dt + ".jpg");
Applog.Log(
TAG,
"New Camera Image Path:- "
+ Environment.getExternalStorageDirectory()
+ "/foldername/" + "Camera_" + dt + ".jpg");
File file = new File(Environment.getExternalStorageDirectory()
+ "/foldername");
if (!file.exists()) {
file.mkdir();
}
if (!imageFile.exists()) {
try {
imageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
imagePath = Environment.getExternalStorageDirectory() + "/foldername/"
+ "Camera_" + dt + ".jpg";
imageUri = Uri.fromFile(imageFile);
return imageUri;
}
Now When you start activty for camera.
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(
MediaStore.EXTRA_OUTPUT,
getTempUri());
startActivityForResult(cameraIntent,
CAMERA_REQUEST_CODE);
Now In ActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (CAMERA_REQUEST_CODE == requestCode && resultCode == RESULT_OK) {
String yourUri=ImagePath;
//now store this Uri it will contain capture image url.
}
}

Categories

Resources