将图像保存在Android设备的特定文件夹中

时间:2017-01-22 08:09:44

标签: android camera

在我的应用程序中,我可以拍照并保存在库中(文件夹'相机')。但我需要将其保存在外部存储器中的特定文件夹中。这是我的代码。我该怎么做它?

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.get_pic);
    init();


    getPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 0);

        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

   if (resultCode == RESULT_OK) {

       Bundle ex = data.getExtras();
        bitmap = (Bitmap) ex.get("data");
        myPic.setImageBitmap(bitmap);
    }
}

1 个答案:

答案 0 :(得分:0)

这应该这样做:

private void createDirectoryAndSaveFile(Bitmap imgSave, String fileName) {

    File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");

    if (!direct.exists()) {
        File imageDirectory = new File("/sdcard/DirName/");
        imageDirectory.mkdirs();
    }

    File file = new File(new File("/sdcard/DirName/"), fileName);
    if (file.exists()) {
        file.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        imgSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}