无法在Android中保存相机图像

时间:2013-08-13 20:59:23

标签: android android-camera

我正在尝试从相机中保存图像。但它不起作用..

获得许可                    

代码粘贴在下面。不知道为什么它不保存图像代码似乎很好从developer.android网站。请帮忙!

   public class CameraActivity extends Activity {

private Camera mCamera;
private CameraPreview mPreview;
private Display display;
private int PreviewSizeWidth = 640;
private int PreviewSizeHeight= 480;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

    // Create an instance of Camera
    mCamera = getCameraInstance();

    // Create our Preview view and set it as the content of our activity.
    mPreview = new CameraPreview(this, mCamera,getWindowManager().getDefaultDisplay());
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mPreview);
    Button captureButton = (Button) findViewById(R.id.button1);
    captureButton.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // get an image from the camera
                    Log.d("Take","Picture");
                    mCamera.takePicture(null, null, mPicture);
                   // mCamera.stopPreview();
                   // mCamera.startPreview();
                }
            }
     );
}

private PictureCallback mPicture = new PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        Log.d("TAG","Callabaclk start");
        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);;
        if (pictureFile == null){
            Log.d("TAG", "Error creating media file, check storage permissions: ");
            return;
        }

        try {
           FileOutputStream fos = new FileOutputStream(pictureFile);
           Log.d("Ok",pictureFile.getAbsolutePath());
           Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
           bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            //fos.write(data);
            fos.flush();
            fos.close();
            Log.d("TAG","DONE");
        } catch (FileNotFoundException e) {
            Log.d("Test", "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d("Test", "Error accessing file: " + e.getMessage());
        } 
    }
};
public static Camera getCameraInstance(){
    Camera c = null;
    try {
        Log.d("Test",Camera.getNumberOfCameras()+"");
        c = Camera.open(); // attempt to get a Camera instance

    }
    catch (Exception e){
        Log.d("test", e.toString());
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}



public static boolean checkCameraHardware(Context context) {
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}

private static File getOutputMediaFile(int type){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

   // File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
           //   Environment.DIRECTORY_PICTURES), "MyCameraApp");
    File sampleDir = Environment.getExternalStorageDirectory();
    File mediaStorageDir = new File(sampleDir.getPath()+File.separator+"Path");

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

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

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE){
       // mediaFile = new File(mediaStorageDir.getPath() + File.separator +"Path_"+ timeStamp + ".jpg");
         mediaFile = new File(mediaStorageDir.getPath() ,"Path_"+ timeStamp + ".jpg");
    } else if(type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
        "VID_"+ timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

}

当我做getPath()时,我得到08-14 02:31:52.153:D / Ok(4279):/ storage /emulated/0 / Path / Path_20130814_023152.jpg

2 个答案:

答案 0 :(得分:4)

经过大量研究后发现需要在fos.close之后添加这些行:

File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Path");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
Uri.parse("file://"+ mediaStorageDir)));

由于 恩乔伊

答案 1 :(得分:2)

检查权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

尝试创建一个简单的文件

 String path = Environment.getExternalStorageDirectory() + "/" + "test.jpg";
 File file = new File(path);
 if (!file.exists()) {
       try {
         file.createNewFile();
       } catch (IOException e) {
                // TODO Auto-generated catch block
         e.printStackTrace();
       }
 }

然后验证您是否可以保存图片