Не получается сохранить изображение на SD карту. Скажите пожалуйста, в чем проблема?
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button take_photo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
take_photo = (Button) findViewById(R.id.take_photo);
take_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String folderToSave = Environment.getExternalStorageDirectory().toString();
SavePicture(imageView,folderToSave);
}
});
}
private String SavePicture(ImageView imageView, String folderToSave)
{
OutputStream fOut = null;
Time time = new Time();
time.setToNow();
try {
File file = new File(folderToSave, Integer.toString(time.year) + Integer.toString(time.month) + Integer.toString(time.monthDay) + Integer.toString(time.hour) + Integer.toString(time.minute) + Integer.toString(time.second) +".jpg"); // создать уникальное имя для файла основываясь на дате сохранения
fOut = new FileOutputStream(file);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // сохранять картинку в jpeg-формате с 85% сжатия.
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName()); // регистрация в фотоальбоме
Toast.makeText(getApplicationContext(),"Save!",Toast.LENGTH_SHORT).show();
}
catch (Exception e) // здесь необходим блок отслеживания реальных ошибок и исключений, общий Exception приведен в качестве примера
{
return e.getMessage();
}
return "";
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="300dp"
android:layout_height="180dp"
android:src="@drawable/dummyphoto"/>
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take Photo"
android:background="@color/colorAccent"
android:textColor="#fff"
android:textSize="22sp"
android:textAllCaps="false"
android:layout_margin="15dp"
android:padding="8dp"/>
</LinearLayout>```
`<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>` - тоже поключил