0

I am trying to save an Imgefile from a picture taken from the camera with high resolution. Unfortunatly no file is beeing created. I don't know where the error lies.

public void saveImage(Bitmap imageFile) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageName = "Image_" + timeStamp;

try {
String path = getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString();
File saveImage = new File(path + File.separator + imageName + ".jpg");
FileOutputStream out = new FileOutputStream(saveImage);
imageFile.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();

} catch (IOException e) {
e.printStackTrace();
}
}

In AndroidManifest.xml i have set the permission to write to external storage.

<manifest>
[...]
    <uses-feature
        android:name="android.hardware.Camera"
        android:required="false" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.Camera.autofocus" />

    <application
       [...]>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.android.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path" ></meta-data>
        </provider>
[...]
</manifest>
Malik
  • 1
  • 2
  • 1
    "Unfortunatly no file is beeing created" -- how are you checking this? Start with `adb shell` or Android Studio's Device File Explorer. If those do not show your file, check Logcat for a stack trace associated with an exception. If those *do* show your file, you need to use `MediaScannerConnection` and its `scanFile()` method to update the `MediaStore` so other things can find out about the new content. – CommonsWare Jul 21 '19 at 14:13
  • I run the app on an Emulator. There i look with the file explorer application for a new created file in the application folder. There are no newly created files. – Malik Jul 21 '19 at 14:20
  • Try `adb shell` or Android Studio's Device File Explorer. – CommonsWare Jul 21 '19 at 14:21
  • You were right. I looked with the Android Studios Device File Explorer and i saw many images that where createt, but that didn't show. With your help i made a method with MediaScannerConnection and now the files are beeing saved as wished. Thank you very much! – Malik Jul 21 '19 at 17:16

1 Answers1

1

Create new file before writing to it (as FileOutputStream requires existing file to open):

File saveImage = new File(path + File.separator + imageName + ".jpg");
saveImage.createNewFile();  /// <--- add this line
FileOutputStream out = new FileOutputStream(saveImage);
S-Sh
  • 3,564
  • 3
  • 15
  • 19