Camera Orientation is not Proper in android - android

I am using custom camera and surface view for capturing image but the problem is the camera orientation is not proper, following is my code and sorry for my bad English communication.
public class Camera_Activity extends Activity implements
SurfaceHolder.Callback {
private Camera camera = null;
private SurfaceView cameraSurfaceView = null;
private SurfaceHolder cameraSurfaceHolder = null;
private boolean previewing = false;
private Display display = null;
private static int wid = 0, hgt = 0;
private LayoutInflater layoutInflater = null;
private View cameraViewControl = null;
private LayoutParams layoutParamsControl = null;
private Button btnCapture = null;
ImageView mImgView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
display = getWindowManager().getDefaultDisplay();
wid = display.getWidth();
hgt = display.getHeight();
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.camera);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
mImgView1.setImageResource(R.drawable.first_leg);
cameraSurfaceView = (SurfaceView) findViewById(R.id.cameraSurfaceView);
cameraSurfaceHolder = cameraSurfaceView.getHolder();
cameraSurfaceHolder.addCallback(this);
cameraSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
layoutInflater = LayoutInflater.from(getBaseContext());
layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
cameraViewControl = layoutInflater.inflate(R.layout.cambutton, null);
this.addContentView(cameraViewControl, layoutParamsControl);
cameraViewControl = layoutInflater.inflate(R.layout.vampireimage, null);
this.addContentView(cameraViewControl, layoutParamsControl);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.takePicture(cameraShutterCallback,
cameraPictureCallbackRaw, cameraPictureCallbackJpeg);
}
});
}
ShutterCallback cameraShutterCallback = new ShutterCallback() {
#Override
public void onShutter() {
// TODO Auto-generated method stub
System.out.println("Hello Shutter");
}
};
PictureCallback cameraPictureCallbackRaw = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
System.out.println("Hello Picture");
}
};
PictureCallback cameraPictureCallbackJpeg = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
Bitmap cameraBitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
wid = cameraBitmap.getWidth();
hgt = cameraBitmap.getHeight();
Bitmap newImage = Bitmap.createBitmap(wid, hgt,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newImage);
canvas.drawBitmap(cameraBitmap, 0f, 0f, null);
Constants.mImageBitmap.clear();
Constants.mImageBitmap.add(cameraBitmap);
File storagePath = new File(
Environment.getExternalStorageDirectory() + "/Photos/");
storagePath.mkdirs();
File myImage = new File(storagePath, "1.jpg");
try {
FileOutputStream out = new FileOutputStream(myImage);
newImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
Log.d("In Saving File", e + "");
} catch (IOException e) {
Log.d("In Saving File", e + "");
}
camera.startPreview();
newImage.recycle();
newImage = null;
// cameraBitmap.recycle();
// cameraBitmap = null;
Intent mInPreview = new Intent(Camera_Activity.this,
Preview_Activity.class);
mInPreview.putExtra("Value", "First");
startActivity(mInPreview);
finish();
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
System.out.println("Hello 2");
}
try {
Camera.Parameters parameters = camera.getParameters();
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
.getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
parameters.setPreviewSize(height, width);
camera.setDisplayOrientation(90);
}
if (display.getRotation() == Surface.ROTATION_90) {
parameters.setPreviewSize(width, height);
}
if (display.getRotation() == Surface.ROTATION_180) {
parameters.setPreviewSize(height, width);
}
if (display.getRotation() == Surface.ROTATION_270) {
parameters.setPreviewSize(width, height);
camera.setDisplayOrientation(180);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(cameraSurfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
camera = Camera.open();
} catch (RuntimeException e) {
Toast.makeText(
getApplicationContext(),
"Device camera is not working properly, please try after sometime.",
Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("Hello 3");
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("3DSoles");
alert.setMessage("Do U Want to Exit?");
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("3DSoles");
alert.setMessage("Do U Want to Exit?");
alert.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
}
return super.onKeyDown(keyCode, event);
}
}

Camera class is not expected to support setPreview(height, width)
see http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation%28int%29 for the official way to choose Camera.setDisplayOrientation()
Starting from API 14 (ICS and higher), camera is expected to support setDisplayOrientation() without
interrupting preview.
For older platforms, I would recommend to disable change of orientation while the camera preview is active; reset of camera (stopPreview() + startPreview) may take too long for UX to be freiendly. Often, preview activities either work with fixed orientation or "simulate" in software orientation change in response to accelerometer events.

Related

How to Capture Screenshot of an Surface View

public class CustomCameraActivity extends Activity implements
SurfaceHolder.Callback {
Camera camera = null;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
int flag = 0;
int which = 0;
Handler handler;
private boolean hasFlash;
private boolean isLighOn;
private Bitmap surfaceBitmap;
private Bitmap cameraBitmap;
private VerticalSeekBar greenSeekbar;
int vesion = 0;
public void turn() {
// myCamera is the Camera object
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
// only for android older than gingerbread
if (Camera.getNumberOfCameras() >= 2) {
vesion = 1;
camera.stopPreview();
camera.release();
// "which" is just an integer flag
switch (which) {
case 0:
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
which = 1;
break;
case 1:
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
which = 0;
break;
}
try {
camera.setPreviewDisplay(surfaceHolder);
// "this" is a SurfaceView which implements
// SurfaceHolder.Callback,
// as found in the code examples
camera.setPreviewCallback(null);
// camera.setPreviewCallback(this);
camera.startPreview();
} catch (IOException exception) {
camera.release();
camera = null;
}
vesion = 1;
} else {
AlertDialog.Builder ab = new AlertDialog.Builder(
CustomCameraActivity.this);
ab.setMessage("Device Having Only one Camera");
ab.setCancelable(false);
ab.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
}).show();
}
} else {
AlertDialog.Builder ab1 = new AlertDialog.Builder(
CustomCameraActivity.this);
ab1.setMessage("This Device Does Not Support Dual Camera Feature");
ab1.setCancelable(false);
ab1.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Constants.data1 = data;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(3);
this.surfaceView.setBackgroundColor(Color.argb(100, 0,
MotionEventCompat.ACTION_MASK, 0));
Button cap_btn = (Button) findViewById(R.id.button01);
Button retake = (Button) findViewById(R.id.retake);
Button use = (Button) findViewById(R.id.Use);
Button back = (Button) findViewById(R.id.back);
Button home = (Button) findViewById(R.id.home);
Button turn = (Button) findViewById(R.id.turn);
turn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
turn();
}
});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flash();
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
use.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (flag >= 1) {
startActivity(new Intent(CustomCameraActivity.this,
Captured.class));
} else {
AlertDialog.Builder ab1 = new AlertDialog.Builder(
CustomCameraActivity.this);
ab1.setMessage("Please Capture Image");
ab1.setCancelable(false);
ab1.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
}).show();
}
flag = 0;
}
});
retake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.startPreview();
flag = 0;
}
});
cap_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.takePicture(null, null, mPicture);
flag++;
}
});
}
public void flash() {
this.hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature("android.hardware.camera.flash");
if (this.hasFlash) {
Parameters p = camera.getParameters();
if (this.isLighOn) {
p.setFlashMode("off");
camera.setParameters(p);
camera.stopPreview();
camera.startPreview();
this.isLighOn = false;
return;
}
p.setFlashMode("torch");
camera.setParameters(p);
camera.stopPreview();
camera.startPreview();
this.isLighOn = true;
return;
}
}
#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();
}
}
}
void setCameraDisplayOrientation(Activity activity, int cameraId,
Camera camera) {
if (camera != null) {
int result;
CameraInfo info = new CameraInfo();
int degrees = 0;
switch (activity.getWindowManager().getDefaultDisplay()
.getRotation()) {
case 0:
degrees = 0;
break;
case 1:
degrees = 90;
break;
case 2:
degrees = 180;
break;
case 3:
degrees = 270;
break;
}
if (info.facing == 1) {
result = (360 - ((info.orientation + degrees) % 360)) % 360;
} else {
result = ((info.orientation - degrees) + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (vesion == 1) {
Camera.open(which);
} else {
camera = Camera.open();
}
} catch (Exception e) {
camera.release();
}
try {
Parameters parameters = camera.getParameters();
if (getResources().getConfiguration().orientation != 2) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(this.surfaceHolder);
} catch (IOException e2) {
camera.release();
}
camera.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
public void joinBitmap() {
this.surfaceView.setBackgroundColor(-16711936);
this.surfaceView.setDrawingCacheEnabled(true);
this.surfaceView.buildDrawingCache();
this.surfaceView.refreshDrawableState();
new Thread() {
public void run() {
try {
CustomCameraActivity.this.surfaceBitmap = CustomCameraActivity.this.surfaceView
.getDrawingCache();
if (CustomCameraActivity.this.surfaceBitmap != null) {
File pictureFile = CustomCameraActivity
.getOutputMediaFile();
if (pictureFile != null) {
Bitmap finalbitmap = CustomCameraActivity.overlay(
CustomCameraActivity.this.cameraBitmap,
CustomCameraActivity.this.surfaceBitmap,
CustomCameraActivity.this.greenSeekbar
.getProgress() + 15);
if (pictureFile.exists()) {
pictureFile.delete();
}
try {
FileOutputStream out = new FileOutputStream(
pictureFile);
finalbitmap.compress(CompressFormat.JPEG, 90,
out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
} catch (IOException e2) {
}
CustomCameraActivity.this.handler
.sendEmptyMessage(1);
return;
}
return;
}
CustomCameraActivity.this.handler.sendEmptyMessage(0);
} catch (Exception e3) {
}
}
}.start();
}
#SuppressLint({ "SimpleDateFormat" })
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
"Night Vision Camera");
if (mediaStorageDir.exists() || mediaStorageDir.mkdirs()) {
return new File(
mediaStorageDir.getPath()
+ File.separator
+ "IMG_"
+ new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date()) + ".jpg");
}
return null;
}
public static Bitmap overlay(Bitmap bitmap1, Bitmap bitmapOverlay,
int opacity) {
Bitmap resultBitmap = Bitmap.createBitmap(bitmapOverlay.getWidth(),
bitmapOverlay.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(resultBitmap);
c.drawBitmap(bitmap1, 0.0f, 0.0f, null);
Paint p = new Paint();
p.setAlpha(opacity);
c.drawBitmap(bitmapOverlay, 0.0f, 0.0f, p);
return resultBitmap;
}
}
Here, I`m creating an image overlay on surface view and when i click on image to capture it, how to save it with that image that is overlayed on it? Please help and thanks in Advance. The image is captured but it is not saved with that image that is overlayed on the surface view.
You can use surfaceview.getDrawingCache();
this will return a Bitmap from your SurfaceView and then you can use it or save it in storage.
surfaceview.getDrawingCache(); does not work on surface, because surface is separate view than others view you have to get bitmpa on picturetaken method.
jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
camera.startPreview();
Bitmap cameraBitmap = BitmapFactory.decodeByteArray
(data, 0, data.length);
Matrix matrix = new Matrix();
matrix.postRotate(90);
pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setTitle("Wait!");
pd.setMessage("capturing image.........");
pd.setIndeterminate(false);
pd.show();
progressStatus = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
// Update the progress status
progressStatus += 1;
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
// Update the progress status
pd.setProgress(progressStatus);
// If task execution completed
if (progressStatus == 100) {
// Dismiss/hide the progress dialog
pd.dismiss();
}
}
});
}
}
}).start();
Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
if (rotatedBitmap != null) {
rotatedBitmap = combinebitmap(rotatedBitmap, bitmapMap);
Random num = new Random();
int nu = num.nextInt(1000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
String picId = String.valueOf(nu);
String myfile = "Ghost" + picId + ".jpeg";
File dir_image = new File(Environment.getExternalStorageDirectory() +//<---
File.separator + "LiveCamera"); //<---
dir_image.mkdirs(); //<---
try {
File tmpFile = new File(dir_image, myfile);
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Toast.makeText(getApplicationContext(),
" Image saved at :LiveCamera", Toast.LENGTH_LONG).show();
camera.startPreview();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(MainActivity.this,
new String[]{dir_image.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
safeToTakePicture = true;
}
}
};

Why image is being saved in Landscape Mode?

In my code all is going well but clicked Image is being saved in Landscape Mode in given Directory. I have tried my best. Please help and suggest me to resolve this issue.
The complete Code is given below with Print screen.
or download from here
https://www.dropbox.com/sh/vp6ohly4zb5vmvq/AACOyS8PvsRxFGBP9zjlVWhza?dl=0
Image saved in SDcard even captured in portrait it appear in landscape
public class AndroidCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//camera.enableShutterSound(true);
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.control, 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);
}});
}
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);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/cam_Api");
myDir.mkdirs();
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/cam_Api/cam_Ap1_%d.jpg", System.currentTimeMillis()));
outStream.write(arg0);
outStream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
}
Toast.makeText(getApplicationContext(), "Picture Saved", Toast.LENGTH_LONG).show();
refreshCamera();
// File file = new File(Environment.getExternalStorageDirectory(),"/cam_Api/MyPhoto2.jpg");
}};
public void refreshCamera() {
if (surfaceHolder.getSurface() == null) {
return;
}
try {
camera.stopPreview();
}
catch (Exception e) {
}
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
catch (Exception e) {
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
camera.setDisplayOrientation(90);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
It seems you are calling:
camera.setDisplayOrientation(90);
which would probably cause the landscape image you are seeing when your application is in portrait mode.
You should use:
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
to get the rotation of your display and then set:
caemra.setDisplayOrientation(rotation);
or just call camera.setDisplayOrientation(0) and set screenOrientation in your android manifest as so:
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
to prevent the orientation changing.
you need to rotate the image and then save it.
public static Bitmap rotateImage(Bitmap bitmapSrc) {
Matrix matrix = new Matrix();
matrix.postRotate(CameraConfigurationUtils.previewRotation);
return Bitmap.createBitmap(bitmapSrc, 0, 0,
bitmapSrc.getWidth(), bitmapSrc.getHeight(), matrix, true);
}
To get the rotation:
private static int setCameraDisplayOrientation(Context mContext, android.hardware.Camera.CameraInfo info) {
int rotation = ((CameraActivity) mContext).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;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
previewRotation = (info.orientation + degrees) % 360;
previewRotation = (360 - previewRotation) % 360; // compensate the mirror
} else { // back-facing
previewRotation = (info.orientation - degrees + 360) % 360;
}
return previewRotation;
}

Taking more than one shots with Android programmatically?

I need to use camera without preview and take more than one shots.
I have written my code and I am able to take one shot, it works properly.
But I could not handle to do more than once. Because the logic of Camera Service i tried a method CreateCameraTakeShot, still no success.
Could you please help me with that?
Here is my code;
public class ContinuingCallActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
FileOutputStream outStream;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_continuingcall);
//getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// for(int i=0;i<10;i++)
//{
mHandler.postDelayed(mLaunchTask, 1000);
//}
}
Handler mHandler = new Handler();
private Runnable mLaunchTask = new Runnable() {
#Override
public void run() {
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
//createCameraTakeShot();
}
};
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);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/MySight/";
File newdir = new File(dir);
newdir.mkdirs();
Date d = new Date();
CharSequence dateOfShot = DateFormat.format("dd-MM-yy hh:mm:ss", d.getTime());
String file = dir+dateOfShot+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outStream = new FileOutputStream(newfile);
outStream.write(bytes.toByteArray());
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + arg0.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public void createCameraTakeShot()
{
camera = Camera.open();
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
camera.stopPreview();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
//camera.release();
//camera = null;
previewing = false;
}
}
you can use timer task insted of handler to take picture prodically
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 1000, 1000);
}
class MyTimerTask extends TimerTask {
public void run() {
// ERROR
camera.takePicture(null,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);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/MySight/";
File newdir = new File(dir);
newdir.mkdirs();
Date d = new Date();
CharSequence dateOfShot = DateFormat.format("dd-MM-yy hh:mm:ss", d.getTime());
String file = dir+dateOfShot+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outStream = new FileOutputStream(newfile);
outStream.write(bytes.toByteArray());
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + arg0.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public void createCameraTakeShot()
{
camera = Camera.open();
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
//camera.release();
//camera = null;
previewing = false;
}
}

Rename image name to datetime stamp

How do i change the codes so that the image's name will be save as date time stamp?
Button buttonTakePicture;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */ #Override public
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_layout);
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.camera_control, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); this.addContentView(viewControl, layoutParamsControl);
buttonTakePicture = (Button) findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG); } });
LinearLayout layoutBackground = (LinearLayout)
findViewById(R.id.background);
layoutBackground.setOnClickListener(new
LinearLayout.OnClickListener() { public void onClick(View arg0) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(false);
camera.autoFocus(myAutoFocusCallback); } }); }
AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback() {
public void onAutoFocus(boolean arg0, Camera arg1) { // TODO
Auto-generated method stub buttonTakePicture.setEnabled(true); }
};
ShutterCallback myShutterCallback = new ShutterCallback() { public
void onShutter() { // TODO Auto-generated method stub
} };
PictureCallback myPictureCallback_RAW = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) { // TODO
Auto-generated method stub
} };
PictureCallback myPictureCallback_JPG = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) { // TODO
Auto-generated method stub /*
* Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0,
* arg0.length);
*/
Uri uriTarget = getContentResolver().insert(
Media.EXTERNAL_CONTENT_URI, new ContentValues()); OutputStream imageFileOS; try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(CameraActivity.this,"Image saved: " + uriTarget.toString(),Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace(); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); } camera.startPreview(); } };
public void surfaceChanged(SurfaceHolder holder, int format, int
width,int height) { // TODO Auto-generated method stub if
(previewing) { camera.stopPreview(); previewing = false; }
if (camera != null) { try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true; } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); } } }
public void surfaceCreated(SurfaceHolder holder) { // TODO
Auto-generated method stub camera = Camera.open(); }
public void surfaceDestroyed(SurfaceHolder holder) { // TODO
Auto-generated method stub camera.stopPreview(); camera.release();
camera = null; previewing = false; } }
I think you could use Content Resolver to achieve it,
ContentValues v = new ContentValues();
v.put(Images.Media.TITLE, title);
v.put(Images.Media.DISPLAY_NAME, System..currenttimemillis());
v.put(Images.Media.DESCRIPTION, description);
v.put(Images.Media.DATE_ADDED, dateTaken);
v.put(Images.Media.DATE_TAKEN, dateTaken);
v.put(Images.Media.DATE_MODIFIED, dateTaken) ;
v.put(Images.Media.MIME_TYPE, “image/jpeg”);
v.put(Images.Media.ORIENTATION, orientation);
Give it a try.
This might help
private void SaveImage(Bitmap finalBitmap, String retailerArray2) {
long timeStamp = Calendar.getInstance().getTimeInMillis();
String dateStamp = DateHelper.dateTime(timeStamp,
"dd-MM-yyyy HH:mm[:ss]");
File myDirectory = new File(root + "/ Gallery/" );
if (!myDirectory.exists()) {
myDirectory.mkdirs();
}
String fname = Name + " -- " + dateStamp + ".jpg";
File file = new File(myDirectory, fname);
}

Android Save Image to SD Card

UPDATE
Added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to the manifest all works ok now.
Ok so I have a app I have started to create which in the end I want to be able to take a picture, which then takes you to another screen which lets you be able to "Use" or "Retake" the picture.
When the image is took it needs to be saved into a new folder on the SD Card, (if the folder is not there then it needs to create it). I had all this working a couple of weeks ago but after i did some editing and shut down eclipse I cant seem to get it back working?
The section for this is after int imageNum = 0; i have added imagesFolder.mkdirs(); which i belive is correct to create a new folder but even this seems not to be working now.
Now the image just gets took and neither the new folder gets created or the image gets saved.
public class AndroidCamera extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
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.control, 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() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
}
});
}
ShutterCallback myShutterCallback = new ShutterCallback() {
public void onShutter() {
// TODO Auto-generated method stub
}
};
PictureCallback myPictureCallback_RAW = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "BeatEmUp");
imagesFolder.mkdirs();
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
You should make sure the manifest lists the permission to write to the SD card:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources