如何使用表面视图无需用户知识捕获图像?

时间:2014-10-25 06:22:40

标签: android android-camera surfaceview

我想从Android相机捕获图像,但没有用户知识。

1 个答案:

答案 0 :(得分:1)

public class Capture extends Activity {

public Uri fileUri;
public String filepath1="";


public static final int DONE=1;  
public static final int NEXT=2;  
public static final int PERIOD=0;  
private Camera camera;  
private int cameraId;     
private Timer timer;  
public static final int MEDIA_TYPE_IMAGE = 2;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.autocapture);  
    try
    {
        cameraMethod();
    }
    catch(Exception e)
    {
        Log.e("camera","Not",e);
    }


}

public void cameraMethod()
{
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {  
    } else {
        android.hardware.Camera.CameraInfo info =new android.hardware.Camera.CameraInfo();
        cameraId = findFrontFacingCamera();

        if (cameraId < 0) {  
        } else {  
            safeCameraOpen(cameraId);   
        }  
    }    

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    SurfaceView view = new SurfaceView(this);  
    try {  
        camera.setPreviewDisplay(view.getHolder());  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
    camera.startPreview();  
    Camera.Parameters params = camera.getParameters();  
    params.setJpegQuality(100);  
    camera.setParameters(params);  
    timer=new Timer(getApplicationContext(),threadHandler);  
    timer.execute();  

}

////////////////////////////////////thread Handler///////////////////////////////////////  
private Handler threadHandler = new Handler() {  
    public void handleMessage(android.os.Message msg) {       
        switch(msg.what){  
        case DONE:  
            // Trigger camera callback to take pic  
            camera.takePicture(null, null, photoCallback);

            break;  
        case NEXT:  
            timer=new Timer(getApplicationContext(),threadHandler);  
            timer.execute();  
            break;  
        }  
    }  
};  
Camera.PictureCallback mCall = new Camera.PictureCallback() {  
    public void onPictureTaken(byte[] data, Camera camera) {  
        //decode the data obtained by the camera into a Bitmap  
        //display.setImageBitmap(photo);  
        Bitmap bitmapPicture = BitmapFactory.decodeByteArray(data, 0, data.length); 

        Message.obtain(threadHandler, Capture.NEXT, "").sendToTarget();   
        //Log.v("MyActivity","Length: "+data.length);  
    }
};  
private int findFrontFacingCamera() {
    int cameraId = 0;
    // Search for the front facing camera
    int numberOfCameras = Camera.getNumberOfCameras();
    for (int i = 1; i < numberOfCameras; i++) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {

            cameraId = i;
        }
        else
        {
            break;
        }
    }
    return cameraId;
}


@Override  
protected void onPause() {  
    if (timer!=null){  
        timer.cancel(true);  
    }  
    releaseCamera();  
    super.onPause();  
}       

private boolean safeCameraOpen(int id) {  
    boolean qOpened = false;  
    try {  
        releaseCamera();  
        camera = Camera.open(id);  
        qOpened = (camera != null);  
    } catch (Exception e) {  
        Log.e(getString(R.string.app_name), "failed to open Camera");  
        e.printStackTrace();  
    }  
    return qOpened;    
}  


private void releaseCamera() {  
    if (camera != null) {  
        camera.stopPreview();  
        camera.release();  
        camera = null;  
    }  
}  


Camera.PictureCallback photoCallback=new Camera.PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {


        OutputStream imageFileOS;


        try {

            imageFileOS = getContentResolver().openOutputStream(fileUri);
            imageFileOS.write(data);
            imageFileOS.flush();
            imageFileOS.close();
            Toast.makeText(Capture.this, "Image saved: " + fileUri, Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }

        String sadf = fileUri.toString();

        Log.e("File url for sd card", ""+sadf);


        Intent myintent1=new Intent(Capture.this,MailSenderGmail1.class);        
        myintent1.putExtra("uris", sadf);
        myintent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(myintent1);
        finish();
    }
};

private static Uri getOutputMediaFileUri(int type){

    return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){

    // Check that the SDCard is mounted
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "TheftImageCapture");

    // Create the storage directory(MyCameraVideo) if it does not exist
    if (! mediaStorageDir.exists()){

        if (! mediaStorageDir.mkdirs()){
            Log.d("MyCameraVideo", "Failed to create directory Theft Image.");

            return null;

        }
    }
    java.util.Date date= new java.util.Date();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
    .format(date.getTime());

    File mediaFile;

    if(type == MEDIA_TYPE_IMAGE) {

        // For unique video file name appending current timeStamp with file name
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_"+ timeStamp + ".jpg");

    } else {
        return null;
    }

    return mediaFile;
}
}

TimerThread Class:

public class Timer extends AsyncTask<Void, Void, Void> {  
Context mContext;  
private Handler threadHandler;  
public Timer(Context context,Handler threadHandler) {  
    super();  
    this.threadHandler=threadHandler;  
    mContext = context;  
}  
@Override  
protected Void doInBackground(Void...params) {   
    try {  
        Thread.sleep(Capture.PERIOD);  
    } catch (InterruptedException e) {  
        e.printStackTrace();  
    }   
    Message.obtain(threadHandler, Capture.DONE, "").sendToTarget();   
    return null;  
}  

}