如何在自定义图库中保存位图?

How to save bitmap in custom gallery?

我了解到我可以在 DCIM 中创建一个文件夹,如果其中有一个文件,该目录将显示为相册名称。我可以很好地创建目录,在这种情况下,我调用目录 "ThoughtCast."

我尝试保存 PNG 文件,但是,没有出现。

这是我的代码:

   public void savebitmap(Bitmap bmp) throws IOException {

        String file_path =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "ThoughtCast/";

        File dir = new File(file_path);
        if(!dir.exists())
            dir.mkdirs();
        File file = new File(dir, "sketchpad"  + ".png");
        FileOutputStream fOut = new FileOutputStream(file);

        bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();

    }

如有任何帮助,我们将不胜感激。谢谢

试试下面的代码。它可能对你有用。

private void saveImageStorage(Bitmap finalBitmap) {
        String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DICM).toString();
        File myDir = new File(root + "/" + <your folder if you want>);
        if(!myDir.exists()){
        myDir.mkdir();
        }

        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Image-" + n + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }


        // inform to the media scanner about the new file so that it is immediately available to the user.
        MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });

    }

试试这个可能对你有帮助(在 kotlin 中)

我目前正在做这个任务

 private fun saveImage(bitmap: Bitmap) {
    var outStream: FileOutputStream? = null
    // Write to SD Card
    try {
        val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "ThoughtCast/")
        dir.mkdirs()
        val fileName = String.format("%s_%d.jpg", "Image", System.currentTimeMillis())
        val outFile = File(dir, fileName)
        outStream = FileOutputStream(outFile)
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
        outStream.flush()
        outStream.close()
        Utils.showSnackBar(binding.rootView, getString(R.string.image_saved))
    } catch (e: FileNotFoundException) {
        Crashlytics.logException(e)
    } catch (e: IOException) {
        Crashlytics.logException(e)
    } finally {
    }
}