Syafiq Rosli Syafiq Rosli - 5 months ago 35
Android Question

Android Studio save image into new directory

My application has 3 buttons: recognize face, gallery and analysis. The recognize button's action is to take a picture. How do I save the picture taken into my gallery directory?

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);
}

}

Answer

Go through the following code , its working fine for me.

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();
}

}

Comments