Android Studio将图像保存到新目录中

时间:2015-11-21 03:55:24

标签: android android-button android-gallery

我的应用程序有3个按钮:识别脸部,图库和分析。识别按钮的动作是拍照。如何将拍摄的照片保存到我的图库目录中?

public class MainMenu extends AppCompatActivity {

    Button btnTakePhoto;
    ImageView imgTakenPhoto;
    private static final int CAM_REQUEST = 1313;

    private static Button button_sbm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_menu);
        OnClickButtonListener();
        btnTakePhoto = (Button) findViewById(R.id.button_recognizeface);
        imgTakenPhoto = (ImageView) findViewById(R.id.imageview1);
        btnTakePhoto.setOnClickListener(new btnTakePhotoClicker());

    }

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

        if(requestCode == CAM_REQUEST)
        {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            imgTakenPhoto.setImageBitmap(thumbnail);
        }

    }


    public void OnClickButtonListener() {
        button_sbm = (Button)findViewById(R.id.button_gallery);
        button_sbm.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View V) {
                        Intent intent = new Intent("com.example.syafiq.facerecognition.Gallery");
                        startActivity(intent);
                    }
                }
        );
    }

    class btnTakePhotoClicker implements Button.OnClickListener
    {

        @Override
        public void onClick(View v) {

            Intent cameraintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraintent, CAM_REQUEST);
        }

    }

1 个答案:

答案 0 :(得分:0)

通过以下代码,它对我来说很好。

private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {

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

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

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

}