从surfaceView捕获Android图片

时间:2014-04-30 11:11:40

标签: android android-camera local-storage

我尝试捕捉图像,在Surfaceview中进行预览,并且有一个按钮,通过该按钮拍摄照片并保存到存储卡中。预览和捕捉效果很好,但无法存储在存储卡上。 有创建的文件,但图片不是一个一个地存储... 请帮我... 我的尝试就在这里......

public class MainActivity extends Activity {
    int TAKE_PHOTO_CODE = 0;
    public static int count=0;

     Camera mCamera;
    private CameraView cameraview;
    RelativeLayout mainlayout;
    ImageView capture;
    ImageView image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        cameraview = new CameraView(this, CameraInfo.CAMERA_FACING_BACK);
        setContentView(R.layout.activity_main);
        mainlayout = (RelativeLayout) findViewById(R.id.mainlayout);
        mainlayout.addView(cameraview);
        capture=(ImageView)findViewById(R.id.capture);
        /////////////////////////////////////////////////////////
         final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/"; 
            File newdir = new File(dir); 
            newdir.mkdirs();


        capture.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
                  //  getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

                cameraview.mCamera.takePicture(shutterCallback, rawCallback,
                           jpegCallback);


                    Toast.makeText(getApplicationContext(), "Captured", 2000).show();

            }
        });
    }



    ShutterCallback shutterCallback = new ShutterCallback() {
        public void onShutter() {
             // Log.d(TAG, "onShutter'd");
        }
  };

  /** Handles data for raw picture */
  PictureCallback rawCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
              //Log.d(TAG, "onPictureTaken - raw");
        }
  };

  /** Handles data for jpeg picture */
  PictureCallback jpegCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
              FileOutputStream outStream = null;
              try {

                    outStream = new FileOutputStream(String.format(
                                "/sdcard/Demo%d.jpg", System.currentTimeMillis()));
                    outStream.write(data);
                    outStream.close();

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

        }
  };



}

我的CameraView类就在这里..

public class CameraView extends SurfaceView implements SurfaceHolder.Callback {

    SurfaceHolder mHolder;
    Camera mCamera;
    int mCameraFacingInfo;
    Context m_context;


    public CameraView(Context context, int camereface) {
        super(context);
        // TODO Auto-generated constructor stub
        m_context = context;
        mCameraFacingInfo = camereface;
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub
        if (mCamera != null) {

            int rotation = ((Activity) m_context).getWindowManager()
                    .getDefaultDisplay().getRotation();
            if (rotation == Surface.ROTATION_0
                    || rotation == Surface.ROTATION_180) {

                mCamera.setDisplayOrientation(90);
            } else if (rotation == Surface.ROTATION_90) {

                mCamera.setDisplayOrientation(0);
            } else if (rotation == Surface.ROTATION_270) {

                mCamera.setDisplayOrientation(180);
            }

            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewSize(width, height);
            // mCamera.setParameters(parameters);
            mCamera.startPreview();
        }

    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub

        // ////////////////////////////////////////////////////
        /*mCamera.setCameraViewDisplay(holder);

        mCamera.setCameraViewCallback(new CameraViewCallback() {

            public void onPreviewFrame(byte[] data, Camera arg1) {
                //
                CameraView.this.invalidate();
            }
        });
*/
        // //////////////////////////////////////////
        synchronized (this) {
            int cameraFacingInfo = -1;
            boolean errorFound = false;

            boolean hasFeatCamera = m_context.getPackageManager()
                    .hasSystemFeature(PackageManager.FEATURE_CAMERA);

            if (hasFeatCamera) {

                try {

                    cameraFacingInfo = mCameraFacingInfo;
                    mCamera = Camera.open(cameraFacingInfo);
                } catch (Exception e) {
                    mCamera = Camera.open(0);
                }

            } else if (CameraInfo.CAMERA_FACING_FRONT > -1) {

                try {
                    cameraFacingInfo = CameraInfo.CAMERA_FACING_FRONT;
                    mCamera = Camera.open(cameraFacingInfo);
                } catch (Exception e) {
                    errorFound = true;

                }

                if (errorFound == true) {
                    try {
                        mCamera = Camera.open(0);
                        cameraFacingInfo = 0;
                    } catch (Exception e) {

                        cameraFacingInfo = -1;
                    }
                }
            }

            if (cameraFacingInfo < 0) {
                Toast.makeText(m_context, "No camera found.", Toast.LENGTH_LONG)
                        .show();
            }

            if (mCamera != null) {
                try {
                    mCamera.setPreviewDisplay(holder);

                    int rotation = ((Activity) m_context).getWindowManager()
                            .getDefaultDisplay().getRotation();
                    if (rotation == Surface.ROTATION_0
                            || rotation == Surface.ROTATION_180) {
                        // Log.i(TAG, "0");
                        mCamera.setDisplayOrientation(90);
                    } else if (rotation == Surface.ROTATION_90) {
                        // Log.i(TAG, "90");
                        mCamera.setDisplayOrientation(0);
                    } else if (rotation == Surface.ROTATION_270) {
                        // Log.i(TAG, "270");
                        mCamera.setDisplayOrientation(180);
                    }

                } catch (IOException exception) {
                    mCamera.release();
                    mCamera = null;
                    // TODO: add more exception handling logic here
                }
            }
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    public void setCameraFacingInfo(int cameraFacingInfo) {
        mCameraFacingInfo = cameraFacingInfo;
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将您的jpegCallback类更改为:

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

    //Creating empty file in sdcard
    File pictureFile = new File(String.format("/sdcard/Demo%d.jpg", System.currentTimeMillis()));
    if (pictureFile == null) {
        Log.e("IMAGE CAPTURE", "Error creating media file, check storage permissions: ");
        return;
    }

    if (data != null) {

        BitmapFactory.Options opts = new BitmapFactory.Options();

        ActivityManager activityManager = (ActivityManager) MainActivity.this.getSystemService(Activity.ACTIVITY_SERVICE);
        int memoryLimit = 100;
        if (activityManager != null) {
            memoryLimit = activityManager.getMemoryClass();
        }

        // Considering memory limitation of device we will resize image to prevent OutOfMemory
        if (memoryLimit < 20) {
            opts.inSampleSize = 6;
        } else if (memoryLimit < 40) {
            opts.inSampleSize = 4;
        } else if (memoryLimit < 64) {
            opts.inSampleSize = 2;
        }

        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
                fos.close();
            }
            bitmap.recycle();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }
}