首页 > 解决方案 > 将图像从 ImageView 保存到存储

问题描述

我按照将图像从 ImageView 保存到内部存储中的答案进行操作,但我仍然无法保存任何内容。我的代码在这里:

 public void buttonPickImage(View view) {

        FileOutputStream fos;

        bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

        Random rng = new Random();
        int n = rng.nextInt(1000);




        try {

            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File(sdCard.getAbsolutePath() + "/BAC");
            bool = dir.mkdir();

            File file = new File(dir, "BAC_"+n+".jpg");


            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
            fos.flush();
            fos.close();
            Toast.makeText(getApplicationContext(),"Image sauvegardée"+bool,Toast.LENGTH_SHORT).show();

        }catch (java.io.IOException e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"IOException: " + e.getMessage(),Toast.LENGTH_SHORT).show();
        }

    }

使用这种方法,我得到带有 messae 的 IOExeception :java.io.FileNotFoundException: /storage/emulated/0/BAC/BAC_396.jpg: open failed: ENOENT (No such file or directory)

我也尝试将其保存到内部存储中,但它对我不起作用: https ://www.tutorialspoint.com/how-to-write-an-image-file-in-internal-storage-in-android 有了这个方法,程序运行但布尔 mkdir 给了我错误。

谢谢你帮助我

标签: androidimageviewstorage

解决方案


终于使用Media Store而不是 getExternalStorageDirectory 让它工作了

此方法在 API 级别 29 中已弃用。为了提高用户隐私,不建议直接访问共享/外部存储设备。当应用程序以 Build.VERSION_CODES.Q 为目标时,从此方法返回的路径不再可供应用程序直接访问。通过迁移到 Context#getExternalFilesDir(String)、MediaStore 或 Intent#ACTION_OPEN_DOCUMENT 等替代方案,应用程序可以继续访问存储在共享/外部存储上的内容。

MediaStore 也很有用,因为它允许您在 android 图库应用中获取图像。

所以我的解决方案是:

ImageView imageView = findViewById(R.id.image);
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "any_picture_name");
        values.put(MediaStore.Images.Media.BUCKET_ID, "test");
        values.put(MediaStore.Images.Media.DESCRIPTION, "test Image taken");
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        OutputStream outstream;
        try {
            outstream = getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, outstream);
            outstream.close();
            Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
        }

仍然感谢@blackapps 向我解释了一些关于 IOexception、mkdir 和 toast 的基本知识。反正会有用的。


推荐阅读