Android:如何将捕获的图像保存到特定文件夹

时间:2014-08-05 09:51:10

标签: android android-camera android-file

我是Android编程的新手,我无法确定如何将图像保存到特定文件夹。让我们说我有一个名为" myCapturedImages"我想将它保存在这个文件夹/目录中。该目录位于Internal Storage\Pictures\myCapturedImages。我拍的照片大小为0字节,无法打开。我认为主要问题是我的onPictureTaken函数。关于如何实现预期的保存目录的任何线索?

PictureCallback myPictureCallback_JPG = new PictureCallback(){

    @Override
    public void onPictureTaken(byte[] arg0, Camera arg1) {
        // TODO Auto-generated method stub
        /*Bitmap bitmapPicture 
            = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);  */

        Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());

        OutputStream imageFileOS;
        try {
            imageFileOS = getContentResolver().openOutputStream(uriTarget);
            imageFileOS.write(arg0);
            imageFileOS.flush();
            imageFileOS.close();

            Toast.makeText(VuzixCamera.this, "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        camera.startPreview();
    }};

2 个答案:

答案 0 :(得分:1)

获取图片的Bitmap,保存Image即可使用此代码

// showedImgae是您的Bitmap图片

public void SaveImage(Bitmap showedImgae){

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/DCIM/myCapturedImages");    
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "FILENAME-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
        FileOutputStream out = new FileOutputStream(file);
        showedImgae.compress(Bitmap.CompressFormat.JPEG, 100, out);
        Toast.makeText(activityname.this, "Image Saved", Toast.LENGTH_SHORT).show();
        out.flush();
        out.close();

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

    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(file);
    mediaScanIntent.setData(contentUri);
    getApplicationContext().sendBroadcast(mediaScanIntent);
}

答案 1 :(得分:1)

这是启动相机并将图片保存到特定文件夹的简单程序......

File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, "image_001.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);

确保您在清单文件中添加了WRITE_EXTERNAL STORAGE和CAMERA权限。