0

我有一个自定义相机,我想将其中捕获的图像保存在我的 SD 卡中的文件夹中。我已经查看了一些示例,但无论出于何种原因,我都没有得到任何保存(文件夹或图像)。下面是我的代码。如果有人可以提供帮助,那就太好了!我已经将 android.permission.WRITE_EXTERNAL_STORAGE 添加到我的清单中。

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub  
                mCamera.takePicture(null, null, mPicture);
    mCamera = getCameraInstance();

        mPreview = new CameraPreview(CameraActivity.this, mCamera);
        FrameLayout preview = (FrameLayout)findViewById(R.id.camera_preview);
        preview.addView(mPreview); 
    }

    private Camera getCameraInstance() {
        // TODO Auto-generated method stub
        Camera c = null;
        try {
            c = Camera.open(); 
        } 
        catch (Exception e) {   
        }
        return c;
    }
    private PictureCallback mPicture = new PictureCallback() {
        public void onPictureTaken(byte[] datas, Camera camera) {
            // TODO Auto-generated method stub  
            File pictureFile = getOutputMediaFile();
            if (pictureFile == null) {
                return;
            } 
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(datas);
                fos.close();
            } catch (FileNotFoundException e) {  

            } catch (IOException e) {                
            }
        }

    };  

        private File getOutputMediaFile() {
            // TODO Auto-generated method stub

            File root = Environment.getExternalStorageDirectory(); 
            File myDir = new File(root + "/NewFolder/");  
            myDir.mkdirs();
            if (myDir.exists()){

            }

            Random generator = new Random(); 
            int n = 10000;
            n = generator.nextInt(n);
            String fname = "Image"+ n +".jpg";
            File file = new File (myDir, fname); 
            Uri uriSavedImage = Uri.fromFile(file);  


            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                    Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
            i.putExtra("output", uriSavedImage);
            return file;

        };
4

2 回答 2

0

我在保存图像时遇到了同样的问题,我们的代码也很相似。我不知道这是否重要,但我使用的是实际设备。对我有用的是在手机上运行项目,断开手机与计算机的连接,然后进行测试。测试后,我可以将手机重新连接到我的电脑,看看图像和文件夹是否在那里。这对我有用,可能对你有帮助。

于 2013-07-13T18:28:10.730 回答
0

首先确保您在清单中提供了 WRITE_EXTERNAL_STORAGE 权限。

在某些手机上,当您从 FileOutputStream 写入文件时,文件不会自动创建,因此您可以尝试以下操作:

try {
                pictureFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(datas);
                fos.close();
            } catch (FileNotFoundException e) {  

            } catch (IOException e) {                
            }

编辑也在一个不相关的注释上,您正在使用的 Random 的实现将始终返回与种子值相同的相同数字。尝试使用 System.getCurrentMillis() 来为您的图像指定一个唯一名称。

于 2013-05-24T17:23:04.310 回答