我正在开发一个相机应用程序。在那显示相机surfaceview。在那,使用前后摄像头拍摄相机surfaceview。当捕获的图像将显示在下一个活动中。一切都很好。在那个默认摄像头是后置摄像头,当点击前面时会再次显示点击开关它会前后移动它是进程。但是当点击开关按钮前置摄像头显示捕获图像时,它会显示在下一个活动中。当按下后退按钮时,它将打开后置摄像头。在切换后打开哪个摄像头,按下后按钮后仍然在那里。我怎样才能做到这一点。有人请帮帮我。
Surfaceview.class
*public class CameraSurface extends SurfaceView implements SurfaceHolder.Callback{
private static final int ORIENTATION_UNKNOWN = 0;
public static Camera camera = null;
public static SurfaceHolder holder = null;
private CameraCallback callback = null;
private boolean isStarted = true;
public static int camId ;
public static int noofcameras;
public static CameraInfo info;
Activity mActivity;
public static SharedPreferences pref;
Camera.Parameters params;
int currentZoomLevel ;
int maxZoomLevel ;
int a;
Editor ed;
Context context;
boolean gg;
int num;
public CameraSurface(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize(context);
}
public CameraSurface(Context context) {
super(context);
initialize(context);
}
public CameraSurface(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
public void setCallback(CameraCallback callback){
this.callback = callback;
}
public void startPreview(){
camera.startPreview();
}
public void startTakePicture(){
if(camera != null)
{
Parameters parameters = camera.getParameters();
/*if(pref.getBoolean("flashlight",true))
{
parameters.setFlashMode(Parameters.FLASH_MODE_ON);
}else
{
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
}
if(pref.getBoolean("flashsound",true))
{
}else
{
}*/
camera.setParameters(parameters);
//camera.setDisplayOrientation(90);
camera.autoFocus(new AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
takePicture();
}
});
}
}
public void takePicture() {
camera.takePicture(
new ShutterCallback() {
@Override
public void onShutter(){
if(null != callback) callback.onShutter();
}
},
new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera){
if(null != callback) callback.onRawPictureTaken(data, camera);
}
},
new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera){
if(null != callback) callback.onJpegPictureTaken(data, camera);
}
});
}
@SuppressLint("NewApi")
public void onOrientationChanged(int orientation) {
if (orientation == ORIENTATION_UNKNOWN) return;
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(camId, info);
orientation = (orientation + 45) / 90 * 90;
int rotation = 0;
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - orientation + 360) % 360;
} /*else { // back-facing camera
rotation = (info.orientation + orientation) % 360;
}*/
params.setRotation(rotation);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
if(null != camera && isStarted)
{
/*int angleToRotate=CommonMethods.getRoatationAngle(mActivity, Camera.CameraInfo.CAMERA_FACING_FRONT);
camera.setDisplayOrientation(angleToRotate);*/
//params=camera.getParameters();
//onOrientationChanged(180);
//setCameraDisplayOrientation(mActivity, camId, camera);
camera.startPreview();
// camera.setDisplayOrientation(90);
}/*else{
camera.startPreview();
}*/
}
@SuppressLint("NewApi")
@Override
public void surfaceCreated(SurfaceHolder holder) {
//a=1;
camId=findCameraID();
noofcameras = Camera.getNumberOfCameras();
info = new CameraInfo();
Camera.getCameraInfo(camId, info);
camera=Camera.open(camId);
// safeCameraOpen(camId);
try {
//camera=Camera.open(camId);
camera.setPreviewDisplay(holder);
params = camera.getParameters();
params.set("orientation", "portrait");
params.setRotation(90);
camera.setDisplayOrientation(90);
camera.setParameters(params);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// isStarted = false;
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
@SuppressWarnings("deprecation")
private void initialize(Context context) {
pref = context.getSharedPreferences("com.example.tattoocameraa", Context.MODE_PRIVATE);
holder = getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// gg=pref.getBoolean("back", true);
//gg=pref.getBoolean("back", false);
}
@SuppressLint("NewApi")
public int findCameraID() {
int foundId = -1;
int numCams = Camera.getNumberOfCameras();
System.out.println("no of cameras are "+numCams);
for (int camId = 0; camId < numCams; camId++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(camId, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
foundId = camId;
break;
}else
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
foundId = camId;
break;
}
}
return foundId;
}
@SuppressLint("NewApi")
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
camera = Camera.open(id);
qOpened = (camera != null);
} catch (Exception e) {
e.printStackTrace();
}
/*if(camera != null)
{
((MainActivity)MainActivity.activity).setSeekbarInitialize(camera.getParameters().getMaxZoom(), camera.getParameters().getZoom());
}*/
return qOpened;
}
@SuppressLint({ "NewApi", "ShowToast" })
public void openFrontFacingCamera() {
//numberOfCamera = Camera.getNumberOfCameras();
if(camId == Camera.CameraInfo.CAMERA_FACING_BACK){
camId = Camera.CameraInfo.CAMERA_FACING_FRONT;
try {
ed=pref.edit();
if(camera!=null)
{
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera=null;
}
camera = Camera.open(camId);
a=2;
//ed.putBoolean("front", true);
ed.putInt("front", 5);
//setCamera(mCamera);
//onOrientationChanged(0);
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.setPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(null != callback) callback.onPreviewFrame(data, camera);
}
});
camera.startPreview();
//previewing = true;
} catch (RuntimeException e) {
}catch (IOException e) {}
}
else if(camId == Camera.CameraInfo.CAMERA_FACING_FRONT){
camId = Camera.CameraInfo.CAMERA_FACING_BACK;
try {
ed=pref.edit();
if(camera!=null)
{
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera=null;
}
camera=Camera.open(camId);
a=1;
//ed.putBoolean("front", false);
ed.putInt("front", 6);
//setCamera(mCamera);
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.setPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(null != callback) callback.onPreviewFrame(data, camera);
}
});
camera.startPreview();
} catch (RuntimeException e) {
}catch (IOException e) {}
}
}
/*@SuppressLint("NewApi")
public void openBackCam() {
//if (gg==false) {
a=1;
ed=pref.edit();
ed.putBoolean("back", false);
try
{
if(camera != null)
{
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
camera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.setPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(null != callback) callback.onPreviewFrame(data, camera);
}
});
camera.startPreview();
}catch(Exception e)
{
}
}
//}
@SuppressLint("NewApi")
public void openFrontCam() {
a=2;
ed=pref.edit();
ed.putBoolean("back", true);
try
{
if(camera != null)
{
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
camera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
//onOrientationChanged(90);
camera.setPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(null != callback) callback.onPreviewFrame(data, camera);
}
});
camera.startPreview();
}catch(Exception e)
{
}
}
*/
public void zoom()
{
params=camera.getParameters();
maxZoomLevel = params.getMaxZoom();
if (currentZoomLevel < maxZoomLevel) {
currentZoomLevel++;
params.setZoom(currentZoomLevel);
camera.setParameters(params);
}
/*if(currentZoomLevel < 50){
params.setZoom(currentZoomLevel= currentZoomLevel + 10);
mCamera.setParameters(params);
}else{
Toast.makeText(getContext(), "no zoom here..",Toast.LENGTH_LONG).show();
}*/
}
public void unzoom()
{
params=camera.getParameters();
maxZoomLevel = params.getMaxZoom();
if (currentZoomLevel > 0) {
currentZoomLevel--;
params.setZoom(currentZoomLevel);
camera.setParameters(params);
}
/*if(currentZoomLevel >0){
params.setZoom(currentZoomLevel= currentZoomLevel - 10);
mCamera.setParameters(params);
}else{
mCamera.setParameters(params);
}
*/
}
public void setZoom(int progress) {
try
{
Parameters parameters = camera.getParameters();
parameters.setZoom(progress);
camera.setParameters(parameters);
}catch(Exception e)
{
}
}
}*
cameraclass.class
public class CameraSwitch extends Activity implements CameraCallback {
private CameraSurface camerasurface = null;
private FrameLayout pannel;
public static Activity activity;
private File f;
public static File mediaFile;
private int screenWidth,screenHeight;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
public static boolean isCapturing = false;
private Button camChange,capture,flashlight;
public static boolean isFrontCamera = false;
private SharedPreferences pref;
private int count;
private RelativeLayout.LayoutParams params;
ImageView imm,aboveimg;
private int[] tattoos;
Button tattooselect,zoomin,zoomout;
GridView gview;
Bitmap backimage;
public RelativeLayout layout;
Bitmap bitmapPicture;
public static File outFile;
public static String fileName;
Camera mcamera;
public static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
Camera.Parameters paramss;
public Editor ee;
boolean bb;
boolean cc;
int ss;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
tattoos = new int[]{
R.drawable.tattoo1, R.drawable.tattoo2,R.drawable.tattoo3,R.drawable.tattoo4,R.drawable.tattoo5,R.drawable.tattoo6,
R.drawable.tattoo7, R.drawable.tattoo8,R.drawable.tattoo9,R.drawable.tattoo10,R.drawable.tattoo11,R.drawable.tattoo12,
R.drawable.tattoo13,R.drawable.tattoo14,R.drawable.tattoo15, R.drawable.tattoo16,R.drawable.tattoo17,R.drawable.tattoo18,
R.drawable.tattoo19,R.drawable.tattoo20, R.drawable.tattoo21,R.drawable.tattoo22,R.drawable.tattoo23,R.drawable.tattoo24,
R.drawable.tattoo25,R.drawable.tattoo26,R.drawable.tattoo27,R.drawable.tattoo28,R.drawable.tattoo29,R.drawable.tattoo30,
R.drawable.tattoo31,R.drawable.tattoo32,R.drawable.tattoo33,R.drawable.tattoo34,R.drawable.tattoo35
};
pref = getSharedPreferences("com.example.tattoocameraa", Context.MODE_PRIVATE);
ee=pref.edit();
/*ee=pref.edit();
ee.putBoolean("vv", false);*/
CameraSwitch.activity = this;
pannel = (FrameLayout)findViewById(R.id.pannel);
layout=(RelativeLayout)findViewById(R.id.relative);
imm=(ImageView)findViewById(R.id.imageView1);
aboveimg=(ImageView)findViewById(R.id.imageView2);
aboveimg.setOnTouchListener(new Touchhimage());
camChange = (Button)findViewById(R.id.button1);
capture = (Button)findViewById(R.id.btnCapture);
//flashlight = (Button)findViewById(R.id.flashlight);
//galleryImage = (ImageView)findViewById(R.id.galleryimg);
tattooselect=(Button)findViewById(R.id.button4);
gview=(GridView)findViewById(R.id.gridview);
zoomin=(Button)findViewById(R.id.button3);
zoomout=(Button)findViewById(R.id.button2);
zoomin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
camerasurface.zoom();
}
});
zoomout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
camerasurface.unzoom();
}
});
tattooselect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
gview.setAdapter(new GridAdapter(getApplicationContext()));
gview.setVisibility(View.VISIBLE);
}
});
gview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "visible", 1000).show();
backimage= BitmapFactory.decodeResource(getResources(), tattoos[position]);
scaling(backimage);
aboveimg.setVisibility(View.VISIBLE);
aboveimg.setImageBitmap(Utils.camerabitmap);
gview.setVisibility(View.INVISIBLE);
}
});
/*if(pref.getBoolean("flashlight",true))
{
flashlight.setBackgroundResource(R.drawable.flash);
}else
{
flashlight.setBackgroundResource(R.drawable.flash2);
}*/
/*if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
flashlight.setVisibility(View.VISIBLE);
}else
{
flashlight.setVisibility(View.GONE);
}
flashlight.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try
{
Editor edit = pref.edit();
if(pref.getBoolean("flashlight",true))
{
edit.putBoolean("flashlight",false);
flashlight.setBackgroundResource(R.drawable.flash2);
}else
{
edit.putBoolean("flashlight",true);
flashlight.setBackgroundResource(R.drawable.flash);
}
edit.commit();
}catch(Exception e)
{
}
}
});*/
if(Camera.getNumberOfCameras()>1)
{
camChange.setVisibility(View.VISIBLE);
}else
{
camChange.setVisibility(View.GONE);
}
camChange.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
camerasurface.openFrontFacingCamera();
/*if(isFrontCamera)
{
//ee.putBoolean("back", true);
camerasurface.openBackCam();
isFrontCamera=false;
}else
{
//ee=pref.edit();
//ee.putBoolean("back", false);
camerasurface.openFrontCam();
isFrontCamera = true;
}*/
}
});
capture.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* if(isCapturing==false)
{
isCapturing=true;
camerasurface.startTakePicture();
//setupPictureMode();
}*/
camerasurface.startTakePicture();
}
});
setupPictureMode();
}
catch(Exception e)
{
}
}
private void setupPictureMode(){
camerasurface = new CameraSurface(this);
pannel.addView(camerasurface, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
camerasurface.setCallback(this);
}
private void resetCam() {
imm.setVisibility(View.INVISIBLE);
camerasurface.startTakePicture();
//isCapturing=true;
//preview.setCamera(camera);
}
public void scaling(Bitmap backimage)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// BitmapFactory.decodeStream(in, null, options);
/// in.close();
// in = null;
// save width and height
// inWidth = options.outWidth;
// inHeight = options.outHeight;
// decode full image pre-resized
// in = new FileInputStream(imageFile.getAbsolutePath());
options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
//options.inSampleSize = Math.max(inWidth/screenWidth, inHeight/screenHeight);
// decode full image
// Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, backimage.getWidth(), backimage.getHeight());
RectF outRect = new RectF(0, 0, screenWidth, screenHeight);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
float[] values = new float[9];
m.getValues(values);
// resize bitmap
Utils.camerabitmap = Bitmap.createScaledBitmap(backimage, imm.getWidth(), imm.getHeight(), true);
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
@Override
public void onShutter() {
// TODO Auto-generated method stub
}
@Override
public void onRawPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
@SuppressLint({ "NewApi", "ShowToast" })
@Override
public void onJpegPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(camId, info);
try
{
File pictureFile = getOutputMediaFile();
if (pictureFile == null ){
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
//Bitmap bitmap = BitmapFactory.decodeFile(pictureFile.getAbsolutePath(), options);
Bitmap bitmap=BitmapFactory.decodeByteArray(data, 0, data.length,options);
if (bitmap != null){
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting post rotate to 90
Matrix mtx = new Matrix();
mtx.postRotate(0);
if(camerasurface.a==1)
{
mtx.postRotate(0);
}
else if (camerasurface.a==2) {
mtx.postRotate(270);
}
Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
//imm.setImageBitmap(bitmap);
imm.setImageBitmap(rotatedBMP);
}
imm.setVisibility(View.VISIBLE);
File file;
layout.getRootView();
layout.setDrawingCacheEnabled(true);
Bitmap m=layout.getDrawingCache();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
file =new File(android.os.Environment.getExternalStorageDirectory(),"WhistleCamera");
if(!file.exists())
{
file.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(count));
f = new File(file.getAbsolutePath()+file.separator+ "IMG_"+timeStamp+".png");
}
FileOutputStream ostream;
try {
ostream = new FileOutputStream(f);
m.compress(CompressFormat.JPEG, 90, ostream);
//m.recycle();
try {
ostream.close();
refreshGallery(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i=new Intent(CameraSwitch.this,Imageshare.class);
i.putExtra("imagepath", f.getAbsolutePath());
startActivity(i);
resetCam();
//camerasurface.startPreview();
//mediaFile.delete();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}catch(Exception e)
{
}finally{
isCapturing = false;
}
}
private Bitmap rotate(Bitmap bitmap, int i) {
// TODO Auto-generated method stub
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(i);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
private static File getOutputMediaFile(){
/*File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "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());
mediaFile = new File(android.os.Environment.getExternalStorageDirectory()+"/WhistleCamera");
if(!mediaFile.exists())
{
mediaFile.mkdirs();
}
mediaFile = new File(android.os.Environment.getExternalStorageDirectory()+"/WhistleCamera",
"filename.jpg");
return mediaFile;
}
@Override
public String onGetVideoFilename() {
// TODO Auto-generated method stub
return null;
}
}
答案 0 :(得分:0)
我希望我能正确理解这个问题。
在onResume()
保存当前正在onPause()