Exemplo n.º 1
0
  @SuppressLint("NewApi")
  public void changeCameraFacing() {
    // 切换前后摄像头
    int cameraCount = 0;
    CameraInfo cameraInfo = new CameraInfo();
    cameraCount = Camera.getNumberOfCameras(); // 得到摄像头的个数

    for (int i = 0; i < cameraCount; i++) {
      Camera.getCameraInfo(i, cameraInfo); // 得到每一个摄像头的信息
      if (cameraPosition == 1) {
        // 现在是后置,变更为前置
        if (cameraInfo.facing
            == Camera.CameraInfo
                .CAMERA_FACING_FRONT) { // 代表摄像头的方位,CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
          mCamera.setPreviewCallback(null);
          mCamera.stopPreview(); // 停掉原来摄像头的预览
          mCamera.release(); // 释放资源
          mCamera = null; // 取消原来摄像头
          mCamera = Camera.open(i); // 打开当前选中的摄像头
          try {
            mCamera.setPreviewDisplay(mHolder); // 通过surfaceview显示取景画面
            initParameters();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          mCamera.startPreview(); // 开始预览
          cameraPosition = 0;
          break;
        }
      } else {
        // 现在是前置, 变更为后置
        if (cameraInfo.facing
            == Camera.CameraInfo
                .CAMERA_FACING_BACK) { // 代表摄像头的方位,CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
          mCamera.setPreviewCallback(null);
          mCamera.stopPreview(); // 停掉原来摄像头的预览
          mCamera.release(); // 释放资源
          mCamera = null; // 取消原来摄像头
          mCamera = Camera.open(i); // 打开当前选中的摄像头
          try {
            mCamera.setPreviewDisplay(mHolder); // 通过surfaceview显示取景画面
            initParameters();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          mCamera.startPreview(); // 开始预览
          cameraPosition = 1;
          break;
        }
      }
    }
  }
Exemplo n.º 2
0
  /**
   * Computes the average frame rate at which the preview callback is called. We will then use this
   * average framerate with the MediaCodec. Blocks the thread in which this function is called.
   */
  private void measureFramerate() {
    final Semaphore lock = new Semaphore(0);

    final Camera.PreviewCallback callback =
        new Camera.PreviewCallback() {
          int i = 0, t = 0;
          long now, oldnow, count = 0;

          @Override
          public void onPreviewFrame(byte[] data, Camera camera) {
            i++;
            now = System.nanoTime() / 1000;
            if (i > 3) {
              t += now - oldnow;
              count++;
            }
            if (i > 20) {
              mQuality.framerate = (int) (1000000 / (t / count) + 1);
              lock.release();
            }
            oldnow = now;
          }
        };

    mCamera.setPreviewCallback(callback);

    try {
      lock.tryAcquire(2, TimeUnit.SECONDS);
      Log.d(TAG, "Actual framerate: " + mQuality.framerate);
      if (mSettings != null) {
        Editor editor = mSettings.edit();
        editor.putInt(
            PREF_PREFIX
                + "fps"
                + mRequestedQuality.framerate
                + ","
                + mCameraImageFormat
                + ","
                + mRequestedQuality.resX
                + mRequestedQuality.resY,
            mQuality.framerate);
        editor.commit();
      }
    } catch (InterruptedException e) {
    }

    mCamera.setPreviewCallback(null);
  }
Exemplo n.º 3
0
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.

    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
    }

    // set preview size and make any resize, rotate or
    // reformatting changes here

    // start preview with new settings
    try {
      Camera.Parameters parameters = mCamera.getParameters();
      setCameraDisplayOrientation(
          ((Activity) this.getContext()), Camera.CameraInfo.CAMERA_FACING_FRONT, mCamera);
      mCamera.setParameters(parameters);

      mCamera.setPreviewCallback(previewCallback);
      mCamera.setPreviewDisplay(mHolder);
      mCamera.startPreview();

    } catch (Exception e) {
      Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
  }
Exemplo n.º 4
0
  public void start() {
    mEncoder = CompressBegin(mVideoParam.width, mVideoParam.height);
    mH264Buff = new byte[mVideoParam.width * mVideoParam.height * 8];

    // save file first for testing
    /*try {
        File file = new File("/sdcard/camera1.h264");
        mRaf = new RandomAccessFile(file, "rw");
    } catch (Exception e) {
        Log.w(TAG, e.toString());
    }*/

    if (mCamera != null) {
      mCamera.setPreviewCallback(
          new Camera.PreviewCallback() {

            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {
              int result = CompressBuffer(mEncoder, 0, data, data.length, mH264Buff);

              // Log.e(TAG, "start to send h264 data");
              try {
                if (result > 0 && mSocket != null && mAddress != null) {
                  DatagramPacket packet = new DatagramPacket(mH264Buff, result, mAddress, 5000);
                  mSocket.send(packet);
                }
              } catch (IOException e) {
                Log.w(TAG, e.toString());
              }

              // Log.e(TAG, "send success!");
            }
          });
    }
  }
        public void onPreviewFrame(byte[] data, Camera camera) {
          Camera.Parameters parameters = camera.getParameters();
          Size size = parameters.getPreviewSize();

          Image barcode = new Image(size.width, size.height, "Y800");
          barcode.setData(data);

          int result = scanner.scanImage(barcode);

          String strScanResult = "";

          if (result != 0) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();

            SymbolSet syms = scanner.getResults();
            for (Symbol sym : syms) {
              // scanText.setText("barcode result " + sym.getData());
              strScanResult += sym.getData();
              barcodeScanned = true;
            }

            Intent myIntent = new Intent(MainActivity.this, ValidateBarCodeResult.class);
            myIntent.putExtra("barcode_result", strScanResult);
            startActivity(myIntent);
          }
        }
Exemplo n.º 6
0
 /**
  * Sets the up camera to be connected to GPUImage to get a filtered preview.
  *
  * @param camera the camera
  * @param degrees by how many degrees the image should be rotated
  * @param flipHorizontal if the image should be flipped horizontally
  * @param flipVertical if the image should be flipped vertically
  */
 public void setUpCamera(
     final Camera camera,
     final int degrees,
     final boolean flipHorizontal,
     final boolean flipVertical) {
   mGlSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
   if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
     setUpCameraGingerbread(camera);
   } else {
     camera.setPreviewCallback(mRenderer);
     camera.startPreview();
   }
   Rotation rotation = Rotation.NORMAL;
   switch (degrees) {
     case 90:
       rotation = Rotation.ROTATION_90;
       break;
     case 180:
       rotation = Rotation.ROTATION_180;
       break;
     case 270:
       rotation = Rotation.ROTATION_270;
       break;
   }
   mRenderer.setRotationCamera(rotation, flipHorizontal, flipVertical);
 }
 private void initCamera() {
   if (!isPreview) {
     camera = Camera.open();
   }
   if (camera != null && !isPreview) {
     streamIt = new StreamIt();
     try {
       Camera.Parameters parameters = camera.getParameters();
       parameters.setPreviewSize(screenWidth, screenHeight); // 设置预览照片的大小	
       parameters.setPreviewFpsRange(20, 30); // 每秒显示20~30帧	
       parameters.setPictureFormat(ImageFormat.NV21); // 设置图片格式	
       parameters.setPictureSize(screenWidth, screenHeight); // 设置照片的大小
       camera.setPreviewDisplay(surfaceHolder); // 通过SurfaceView显示取景画面
       camera.setPreviewCallback(streamIt); // 设置回调的类	
       camera.startPreview(); // 开始预览	
       camera.autoFocus(null); // 自动对焦
     } catch (Exception e) {
       e.printStackTrace();
     }
     isPreview = true;
     Thread postThread2 = new Thread(new postThread());
     postThread2.start();
     System.out.println("线程启动了@@@@@@@@@@@@@@@@@@@@@@@@@@");
   }
 }
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    /*
     * If your preview can change or rotate, take care of those events here.
     * Make sure to stop the preview before resizing or reformatting it.
     */
    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
    }

    try {
      // Hard code camera surface rotation 90 degs to match Activity view in portrait
      mCamera.setDisplayOrientation(90);

      mCamera.setPreviewDisplay(mHolder);
      mCamera.setPreviewCallback(previewCallback);
      mCamera.startPreview();
      mCamera.autoFocus(autoFocusCallback);
    } catch (Exception e) {
      Log.d("DBG", "Error starting camera preview: " + e.getMessage());
    }
  }
Exemplo n.º 9
0
 private void changeMes() {
   preview.removeAllViews();
   mCamera.setPreviewCallback(new PreviewCallback(tv_values3, preview));
   mCamera.startPreview();
   mPreview = new CameraPreview(this, mCamera);
   preview.addView(mPreview);
 }
Exemplo n.º 10
0
  private void startPreview() {
    if (mPausing || mMainActivity.isFinishing()) return;

    ensureCameraDevice();

    // If we're previewing already, stop the preview first (this will blank
    // the screen).
    if (mPreviewing) stopPreview();

    setPreviewDisplay(mSurfaceHolder);
    setCameraParameters();

    // mCameraDevice.setPreviewCallback(mPreviewCallback);
    mCameraDevice.setPreviewCallback(cb);

    try {
      Log.v(TAG, "startPreview");
      mCameraDevice.startPreview();
    } catch (Throwable ex) {
      closeCamera();
      throw new RuntimeException("startPreview failed", ex);
    }
    mPreviewing = true;
    mStatus = IDLE;
  }
Exemplo n.º 11
0
  private void setPreviewCallback() {
    if (mCamera == null) {
      android.util.Log.e("MOSYNC INTERNAL", "No Preview set");
      return;
    }

    try {
      // We have to use and static instance of the camera in the reflection here
      mSetPreviewCallbackWithBuffer =
          mCamera
              .getClass()
              .getMethod("setPreviewCallbackWithBuffer", Camera.PreviewCallback.class);

      Camera.Parameters parameters = getCurrentParameters();
      Camera.Size size = parameters.getPreviewSize();

      mCallbackBuffer = new byte[size.width * size.height * 4];

      mCamera.addCallbackBuffer(mCallbackBuffer);

      mIsUsingPreviewCallbackBuffer = true;

      mCamera.setPreviewCallbackWithBuffer(previewCallback);

    } catch (NoSuchMethodException nsme) {
      mIsUsingPreviewCallbackBuffer = false;

      mCamera.setPreviewCallback(previewCallback);
    }
  }
  public void onPreviewFrame(byte[] data, Camera camera) {
    Camera.Parameters parameters = camera.getParameters();
    Camera.Size size = parameters.getPreviewSize();

    Image barcode = new Image(size.width, size.height, "Y800");
    barcode.setData(data);

    int result = mScanner.scanImage(barcode);

    if (result != 0) {
      mCamera.cancelAutoFocus();
      mCamera.setPreviewCallback(null);
      mCamera.stopPreview();
      mPreviewing = false;
      SymbolSet syms = mScanner.getResults();
      for (Symbol sym : syms) {
        String symData = sym.getData();
        if (!TextUtils.isEmpty(symData)) {
          Intent dataIntent = new Intent();
          dataIntent.putExtra(SCAN_RESULT, symData);
          dataIntent.putExtra(SCAN_RESULT_TYPE, sym.getType());
          setResult(Activity.RESULT_OK, dataIntent);
          finish();
          break;
        }
      }
    }
  }
Exemplo n.º 13
0
  public void surfaceCreated(SurfaceHolder holder) {
    // The Surface has been created, acquire the camera and tell it where
    // to draw.
    camera = Camera.open();
    try {
      camera.setPreviewDisplay(holder);

      camera.setPreviewCallback(
          new PreviewCallback() {

            public void onPreviewFrame(byte[] data, Camera arg1) {
              FileOutputStream outStream = null;
              try {
                outStream =
                    new FileOutputStream(
                        String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
                outStream.write(data);
                outStream.close();
                Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
              } catch (FileNotFoundException e) {
                e.printStackTrace();
              } catch (IOException e) {
                e.printStackTrace();
              } finally {
              }
              Preview.this.invalidate();
            }
          });
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 14
0
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_camera);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mContext = CameraActivity.this;

    mUsersSQL = "select a.[CORPNO], a.[OPERNO], a.[OPERPASS] from b_opera a;";
    mSearchUsersSQL = "select count(*) from b_opera a where a.[CORPNO] = ? and a.[OPERNO] = ?;";
    mInsertOperaSQL = "INSERT INTO B_OPERA (CORPNO, OPERNO, OPERPASS) VALUES(?, ?, ?, ?, ?);";
    mInsertDownInfoSQL =
        "INSERT INTO B_LOGININFO (CORPNO, PROJDESC, DOWNURL, UPLOADURL, DBFILENAME, DOWNTIME) VALUES(?, ?, ?, ?, ?, ?);";
    mDownLoadInfoSQL =
        "select a.[CORPNO], a.[PROJDESC], a.[DOWNURL], a.[UPLOADURL], a.[DBFILENAME] from b_logininfo a;";
    autoFocusHandler = new Handler();
    mCamera = getCameraInstance();

    /* Instance barcode scanner */
    scanner = new ImageScanner();
    scanner.setConfig(0, Config.X_DENSITY, 3);
    scanner.setConfig(0, Config.Y_DENSITY, 3);

    Log.i(TAG, "CameraActivity onCreate()");
    mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
    FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
    preview.addView(mPreview);

    mCamera.setPreviewCallback(previewCb);
    mCamera.startPreview();
    previewing = true;
    mCamera.autoFocus(autoFocusCB);

    // 初始化声音和震动
    AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
    // 如果手机是震动模式就震动
    if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
      playBeep = false;
    }
    // 初始化声音
    initBeepSound();
    initLoginDataBase();
    // MyApp.showToast(CameraActivity.this, "hello");

    Button mButtonBack = (Button) findViewById(R.id.button_back);

    /*返回按钮*/
    mButtonBack.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("downloadfile", "");
            setResult(RESULT_OK, intent);
            finish();
          }
        });
  }
Exemplo n.º 15
0
 @Override
 public void surfaceDestroyed(SurfaceHolder arg0) {
   // TODO Auto-generated method stub
   mDetection.setOnDetectionListener(null);
   mCamera.setPreviewCallback(null);
   mCamera.stopPreview();
   mCamera.release();
 }
Exemplo n.º 16
0
 @Override
 public void surfaceDestroyed(SurfaceHolder holder) {
   // 空,记得在activity中释放摄像头
   mCamera.setPreviewCallback(null);
   mCamera.stopPreview();
   mCamera.release(); // 加上这句,就OK!
   mCamera = null;
 }
Exemplo n.º 17
0
 public void onPause() {
   if (mCamera != null) {
     mCamera.setPreviewCallback(null);
     mCamera.stopPreview();
     mCamera.release();
     mCamera = null;
   }
 }
Exemplo n.º 18
0
 private void releaseCamera() {
   if (mCamera != null) {
     previewing = false;
     mCamera.setPreviewCallback(null);
     mCamera.release();
     mCamera = null;
   }
 }
Exemplo n.º 19
0
 private void stopPreview() {
   if (mCameraDevice != null && mPreviewing) {
     Log.v(TAG, "stopPreview");
     mCameraDevice.setPreviewCallback(null);
     mCameraDevice.stopPreview();
   }
   mPreviewing = false;
 }
Exemplo n.º 20
0
 // 释放相机占用的系统资源
 private void releaseCamera() {
   if (camera != null) {
     camera.setPreviewCallback(null);
     camera.stopPreview();
     camera.release();
     camera = null;
   }
 }
Exemplo n.º 21
0
 // Called when the holder is destroyed
 public void surfaceDestroyed(SurfaceHolder holder) {
   if (camera != null) {
     camera.stopPreview();
     camera.setPreviewCallback(null);
     camera.release();
     camera = null;
   }
 }
Exemplo n.º 22
0
 @Override
 public void surfaceDestroyed(SurfaceHolder arg0) {
   if (mCamera != null) {
     mCamera.setPreviewCallback(null);
     mCamera.stopPreview();
     mCamera.release();
     mCamera = null;
   }
 }
 /** {@inheritDoc} */
 @Override
 public void surfaceCreated(SurfaceHolder holder) {
   try {
     camera.setPreviewDisplay(previewHolder);
     camera.setPreviewCallback(previewCallback);
   } catch (Throwable t) {
     Log.e("PreviewDemo-surfaceCallback", "Exception in setPreviewDisplay()", t);
   }
 }
 public void closeCamera() {
   if (camera == null) {
     return;
   }
   camera.setPreviewCallback(null);
   camera.stopPreview();
   camera.release();
   camera = null;
 }
 private void releaseCamera() {
   if (mCamera != null) {
     mCamera.stopPreview();
     mCamera.setPreviewCallback(null);
     mCamera.release();
     mCamera = null;
     Log.d("", "release preview Camera");
   }
 }
Exemplo n.º 26
0
 /** 停止拍摄 */
 public void stopCapture() {
   start_flag = false;
   if (mCamera != null) {
     mCamera.setPreviewCallback(null);
     mCamera.stopPreview();
     mCamera.release();
     mCamera = null;
   }
 }
Exemplo n.º 27
0
 /** {@inheritDoc} */
 @Override
 public void onPause() {
   super.onPause();
   camera.setPreviewCallback(null);
   if (inPreview) camera.stopPreview();
   inPreview = false;
   camera.release();
   camera = null;
 }
Exemplo n.º 28
0
 public void surfaceDestroyed(SurfaceHolder holder) {
   // Surface will be destroyed when we return, so stop the preview.
   if (mCamera != null) {
     mCamera.stopPreview();
     mCamera.setPreviewCallback(null);
     mCamera.release();
     mCamera = null;
   }
 }
Exemplo n.º 29
0
 /**
  * A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
  * in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
  * respectively.
  *
  * @param handler The handler to send the message to.
  * @param message The what field of the message to be sent.
  */
 public void requestPreviewFrame(Handler handler, int message) {
   if (camera != null && previewing) {
     previewCallback.setHandler(handler, message);
     if (useOneShotPreviewCallback) {
       camera.setOneShotPreviewCallback(previewCallback);
     } else {
       camera.setPreviewCallback(previewCallback);
     }
   }
 }
Exemplo n.º 30
0
 @Override
 public void surfaceCreated(SurfaceHolder holder) {
   try {
     camera.setPreviewDisplay(holder);
     camera.startPreview();
     camera.setPreviewCallback(this);
   } catch (Exception e) {
     debug("surfaceCreated() error!");
   }
 }