Daniele
Daniele

Reputation: 734

Save file to internal storage and show in gallery

I should save an image (byte []) inside the internal memory and make it visible inside the gallery, but the following code does not work, what's wrong? the file is not saved and shown in the gallery but no error is generated

private void saveImageToDisk(final byte[] bytes) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-hh:mm");
    String todayDate = dateFormat.format(new Date());
    Log.d("Foto data: ",todayDate);
    File file = new File(context.getFilesDir(), "image.jpg");
    try (final OutputStream output = new FileOutputStream(file)) {
        output.write(bytes);
        output.close();

    } catch (final IOException e) {
        Log.e("TAG", "Exception occurred while saving picture to storage ", e);
    }



    Log.d("Foto","File salvato"+ file.getAbsolutePath());
    addPicToGallery(file.getPath());

}

private void addPicToGallery(String photoPath) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File file = new File(photoPath);
    Uri contentUri = Uri.fromFile(file);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

Upvotes: 1

Views: 3237

Answers (2)

ravi
ravi

Reputation: 1001

To save an image to internal storage you can use the function below:

String saveImage(Context context, Bitmap image) {

    String savedImagePath = null;

    // Create the new file in the external storage
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + ".jpg";
    File storageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    + "/YourAppName");
    boolean success = true;
    if (!storageDir.exists()) {
        success = storageDir.mkdirs();
    }

    // Save the new Bitmap
    if (success) {
        File imageFile = new File(storageDir, imageFileName);
        savedImagePath = imageFile.getAbsolutePath();
        try {
            OutputStream fOut = new FileOutputStream(imageFile);
            image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Add the image to the system gallery
        galleryAddPic(context, savedImagePath);

        // Show a Toast with the save location
        String savedMessage = context.getString(R.string.saved_message, savedImagePath);
        Toast.makeText(context, savedMessage, Toast.LENGTH_SHORT).show();
    }

    return savedImagePath;
}

This function takes context and Bitmap image as the parameters and returns the path of the file stored.

And to make the image visible to default gallery:

static void galleryAddPic(Context context, String imagePath) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(imagePath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}

You need to pass the context and path of the image stored to this function. This second function is called inside the first function.

And I am not sure if you would need to actually make a FileProvider for these purposes, but if you do.

In you AndroidManifest.xml inside of the <application> tag , use following:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="<YOUR.PACKAGE.NAME>.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

And create a new Resource directory. Right click 'res'>>New Android Resource Directory. Choose 'xml' from the dropdown. Then right click the xml folder and create a file called file_paths wherein put:

    <?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-cache-path name="my_cache" path="." />
    <external-path name="my_images" path="Pictures/" />
</paths>

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006549

Save file to internal storage and show in gallery

That is not possible, sorry.

but the following code does not work, what's wrong?

Third-party apps, including the MediaStore and galleries, have no rights to access your files on internal storage.

Upvotes: 0

Related Questions