Search code examples
javaandroidandroid-bitmap

Android bitmap saving error. saving image is wrong , update gallery after saving image to sd card


I created a function to save a selected image from gallery.I realize that when the image is saved for the first time it is ok.But if the process start again, it seems that the image is saved (with the same name) but the image don't change in the explorer.It just keep the old bitmap image.I tested on two different devices but the same result.Actually on an Infinix hot 7 but same result.

public static String saveImage(Bitmap bitmap, File[] folders, File file, Context context) {

    for (File folder:folders) {
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    if (file.exists ()) {
        file.delete();
    }

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Green tree image

Red tree image

You can see that i chose a photo of green nature but it registers an old red tree photo


Solution

  • After saving the image in gallery you should update image to the system for gallery and file explorer

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));