无法将位图图像保存到Android中的新文件夹

时间:2019-06-07 15:46:13

标签: android bitmap

我正在单击图库中的图像,然后尝试将其保存到新文件夹中,但是出现以下错误,有人可以帮忙吗。

    java.lang.NullPointerException: 
    Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference

调用saveImage函数:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {

        Uri pickedImage = data.getData();

        String[] filePath = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        bitmap = BitmapFactory.decodeFile(imagePath, options);

        cursor.close();
    }
    try {
        saveImage(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
    finish();
}

我的图像保存代码:

    public void saveImage(Bitmap finalBitmap) throws IOException {

            String root = Environment.getExternalStorageDirectory().getAbsolutePath();
            File myDir = new File(root + "/saved_images");
            myDir.createNewFile();

            String imageName = String.format("%d.png", System.currentTimeMillis());
            File file = new File(myDir, imageName);
            if (file.exists()) file.delete();
            try {
                FileOutputStream out = new FileOutputStream(file);
                finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
    }

此行发生错误,finalBitmap始终为null;

    finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);

1 个答案:

答案 0 :(得分:0)

尝试这样做: 将myDir.createNewFile();替换为myDir.mkdirs(); 然后在file.createNewFile();

之后添加以下行:File file = new File(myDir, imageName);

别忘了添加写入外部存储的权限,转到您的android清单并添加:  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 然后在设置中的应用中启用权限