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

时间:2018-08-20 22:04:33

标签: android android-studio android-bitmap android-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();

    }

任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:1)

尝试一下可能会对您有帮助(位于科特林)

我目前正在执行此任务

 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 {
    }
}

答案 1 :(得分:0)

请在下面尝试此代码。它可能对您有用。

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);
                    }
                });

    }