Captured image gets distorted when saved - Android Surfaceholder HTC Desire S - android

I'm using the Surfaceholder and the camera to capture an image but when I do it on my HTC Desire S the captured image looks like this. This is not what it looks like in the preview-view.
It works on two of the other phones I have been testing on so it should be a device dependant issue but I can't figure out what.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_camera_overlay);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
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.overlay, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
...
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] byteArray, Camera arg1) {
//Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String date = dateFormat.format(new Date());
String _path = Environment.getExternalStorageDirectory() + File.separator + "xxx" + File.separator + "Livboj" + date + ".jpg";
File file = new File( _path );
Uri uriTarget = Uri.fromFile( file );
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(byteArray);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(CameraOverlayActivity.this,"Image saved: " + uriTarget.toString(),Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height);
parameters.setPreviewSize(size.width, size.height);
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if(display.getRotation() == Surface.ROTATION_0)
{
camera.setDisplayOrientation(90);
}
if(display.getRotation() == Surface.ROTATION_90)
{
}
if(display.getRotation() == Surface.ROTATION_180)
{
}
if(display.getRotation() == Surface.ROTATION_270)
{
camera.setDisplayOrientation(180);
}
camera.setParameters(parameters);
previewCamera();
}
private Camera.Size getBestPreviewSize(int width, int height)
{
Camera.Size result=null;
Camera.Parameters p = camera.getParameters();
for (Camera.Size size : p.getSupportedPreviewSizes()) {
if (size.width<=width && size.height<=height) {
if (result==null) {
result=size;
} else {
int resultArea=result.width*result.height;
int newArea=size.width*size.height;
if (newArea>resultArea) {
result=size;
}
}
}
}
return result;
}
public void previewCamera()
{
try
{
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
}
catch(Exception e)
{
Log.d("Camera", "Cannot start preview", e);
}
}
I don't know it the problem is in the saving or in the capturing. Has anyone encountered the same problem? Thanks in advance!

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();
}
}

How to make camera photo correct on every device / Android version?

I wrote this camera app, but I cannot got correct image on every device
I found that there are two types camera on different devices, so I cannot rotate photo correctly on every device.
I have looked into some open source camera app, but don't see any logic to handle this problem, and these apps still rotate correctly.
How to detect the type of camera? so that I can rotate photo to correct degree.
public class Camera01 extends Activity implements SurfaceHolder.Callback {
SurfaceHolder surfaceHolder;
SurfaceView surfaceView1;
Button button1;
Camera camera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera01);
button1=(Button)findViewById(R.id.button1);
surfaceView1=(SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder=surfaceView1.getHolder();
surfaceHolder.addCallback(this);
button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
camera.autoFocus(afcb);
}
});
}
PictureCallback jpeg =new PictureCallback(){
public void onPictureTaken(byte[] data, Camera camera) {
new SaveImageTask().execute(data);
camera.startPreview();
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
public void surfaceCreated(SurfaceHolder holder) {
camera=Camera.open(1);
try {
Camera.Parameters params = camera.getParameters();
List<Camera.Size> sizes = params.getSupportedPictureSizes();
params.setPictureFormat(PixelFormat.JPEG);
Camera.Size mSize = sizes.get(0);
params.setPictureSize(mSize.width, mSize.height);
params.setRotation(90); // <<<<<<<<<<<<<<<<<<<<< to correct photo direction
camera.setParameters(params);
camera.setPreviewDisplay(surfaceHolder);
// camera.setDisplayOrientation(90);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
AutoFocusCallback afcb= new AutoFocusCallback(){
public void onAutoFocus(boolean success, Camera camera) {
if(success){
camera.takePicture(null, null, jpeg);
}
}
};
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
#Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
try {
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "test");
if (! dir.exists()){
if (! dir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(outFile));
sendBroadcast(mediaScanIntent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}
}
You can make correct rotation if you have filepath of image with scaled bitmap of image then use below method:
public Bitmap checkRotation(String filePath, Bitmap scaledBitmap) {
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
}
return scaledBitmap;
}

take picture continuously in android

I am new to android. I just downloaded an example camera program. I can take one image each time I click the "capture" button.
Now I want to know if it is possible to take two images continuously (one with flash and one without flash). Does anybody have a hint on how to do that? Thanks a lot.
I posted the sample code here:
public class AndroidCameraExample extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private Button capture, switchCamera;
private Context myContext;
private LinearLayout cameraPreview;
private boolean cameraFront = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
myContext = this;
initialize();
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findBackFacingCamera());
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
public void initialize() {
cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
capture = (Button) findViewById(R.id.button_capture);
capture.setOnClickListener(captrureListener);
switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
switchCamera.setOnClickListener(switchCameraListener);
}
OnClickListener switchCameraListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get the number of cameras
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber > 1) {
//release the old camera instance
//switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
};
public void chooseCamera() {
//if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
protected void onPause() {
super.onPause();
//when on Pause, release camera in order to be used from other applications
releaseCamera();
}
private boolean hasCamera(Context context) {
//check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private PictureCallback getPictureCallback() {
PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//make a new picture file
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
toast.show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
//refresh camera to continue preview
mPreview.refreshCamera(mCamera);
}
};
return picture;
}
OnClickListener captrureListener = new OnClickListener() {
#Override
public void onClick(View v) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
mCamera.setParameters(parameters);
mCamera.takePicture(null, null, mPicture);
}
};
//make picture and save to a folder
private static File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
File mediaStorageDir = new File("/sdcard/", "JCG Camera");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
//and make a media file:
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}

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.
}
}

how can i detect the front camera and use to capture an image?

I have my codes here that captured an image automatically using back camera and saved it to the gallery, my problem is, I want the front camera to use to capture an image. How can i detect the front camera? I really need help for this.
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
iv_image = (ImageView) findViewById(R.id.imageView);
sv = (SurfaceView) findViewById(R.id.surfaceView);
sHolder = sv.getHolder();
sHolder.addCallback(this);
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
//mCamera.startPreview();
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
Uri uriTarget = getContentResolver().insert
(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(TakePictureActivity.this,
"Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
iv_image.setImageBitmap(bmp);
}
};
mCamera.takePicture(null, null, mCall);
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
If you are using API level 9 (Android 2.3) or above, you can do the following to calculate the index of the (first) front-facing camera:
int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}
you can then use the index for the Camera.open method, e.g.:
int index = getFrontCameraId();
if (index == -1) error();
Camera c = Camera.open(index);
To get the relevant camera.
Credits

Categories

Resources