Android Save Pictures to Album No Display Solution of Compatible with Android 10 and later

  • 2021-12-12 05:51:20
  • OfStack

Preface to the table of contents Problem Solve a problem

Preface

I wrote an demo. The simple logic is to add a line of text or watermark to a picture and save it to the system photo album, which is the gallery on our mobile phone. There is no problem in adding watermark to the edited picture before, but there is a problem in saving it to the system photo album: the picture can't be displayed.

Problem

3 Steps to Save System Albums Before Android 10:

Save pictures to mobile phone Insert pictures into the mobile phone gallery Send broadcast updates

The code is as follows:


public static void savePhotoAlbum(Context context, Bitmap bmp) {
    //  Save the picture first 
    File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
    if (!appDir.exists()) {
        appDir.mkdir();
    }
    String fileName = System.currentTimeMillis() + ".jpg";
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bmp.compress(CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
	}
    
    //  Next, insert the file into the system gallery 
    try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
				file.getAbsolutePath(), fileName, null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    //  Finally notify gallery of updates 
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
}

Problem: The picture is not displayed, which means it has not been updated to the system gallery.

Careful friends will find that there are two abandoned methods in the previous code:


 MediaStore.Images.Media.insertImage(context.getContentResolver(),
				file.getAbsolutePath(), fileName, null);

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));

Solve a problem

The following is to solve the above problems and be compatible with Android 10 version:


    /**
     *  Add Watermark and Save to System Album 
     */
    private void imgMerge() {
        new Thread(() -> {
            try {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test);
                File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "newFile.jpg");
                if (!file.exists()) {
                    file.createNewFile();
                }
                // Add watermark text location. 
                Bitmap newBitmap = addTextWatermark(bitmap, " Test demo Example ");
                // Save to System Album 
                savePhotoAlbum(newBitmap, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
    
    /**
     *  Save to Album 
     *
     * @param src   Source picture 
     * @param file  File to save to 
     */
    private void savePhotoAlbum(Bitmap src, File file) {
        if (isEmptyBitmap(src)) {
            return;
        }
        // Save to file first 
        OutputStream outputStream;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            src.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            if (!src.isRecycled()) {
                src.recycle();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // Update the gallery again 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.getName());
            values.put(MediaStore.MediaColumns.MIME_TYPE, getMimeType(file));
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
            ContentResolver contentResolver = getContentResolver();
            Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  values);
            if (uri == null) {
                return;
            }
            try {
                outputStream = contentResolver.openOutputStream(uri);
                FileInputStream fileInputStream = new FileInputStream(file);
                FileUtils.copy(fileInputStream, outputStream);
                fileInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            MediaScannerConnection.scanFile(
                    getApplicationContext(),
                    new String[]{file.getAbsolutePath()},
                    new String[]{"image/jpeg"},
                    (path, uri) -> {
                        // Scan Completed
                    });
        }
    }

Send a broadcast and insert an MediaProvider to add pictures to the album, both of which have been officially discarded. Using the above method in Android 10 and later versions can effectively solve the problem of not displaying pictures.

Make a record!

The above is the Android picture saved to the system photo album does not display the solution (compatible with Android 10 and higher version) details, more about the Android picture saved to the photo album does not display information please pay attention to other related articles on this site!


Related articles: