В вашем методе void initialze()
вызовите функцию saveImagetoGallery
:
public void initialze()
{
imageView = (ImageView)findViewById(R.id.image);
button = (Button) findViewById(R.id.camera);
}
public void takePhoto()
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAPTURE_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch (requestCode)
{
case CAPTURE_PHOTO:
Toast.makeText(this, "Saved to Gallery", Toast.LENGTH_SHORT).show();
bitmap = (Bitmap)data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
saveImagetoGallery(bitmap); // Added this
break;
default:
break;
}
}
}
Функция saveImagetoGallery
:
private void saveImagetoGallery(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root+"/saveImage");
myDir.mkdirs();
Random random = new Random();
int n = 10000;
n = random.nextInt(n);
String imageName = "Image"+n+".jpg";
File file = new File(myDir,imageName);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
if(file.exists())file.delete();
try{
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,90,out);
String string = file.getAbsolutePath();
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Я предполагаю, что вы написали разрешения вфайл Android.Manifest.xml
.
Если у вас его нет, добавьте:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />