有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么图像保存不再在API 29上工作

在我的应用程序中,用户可以通过单击DL按钮将图像从PC图库保存到本地设备

该代码确实适用于旧设备,但在API 29上它具有以下行为: 在保存时,我试图打开图库看看会发生什么:图库被更新,一秒钟后一个空图像出现并立即消失。我注意到,图像被保存了,但它没有出现,甚至没有出现在设备浏览器中

//DEXTER HERE  
Picasso.get().load(dummyimage.getLarge()).placeholder(R.drawable.ic_img_error).error(R.drawable.ic_red).into(saveImageToDirectory);


  final Target saveImageToDirectory = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            ProgressDialog mydialog = new ProgressDialog(getActivity());
            mydialog.setMessage("saving Image to phone");
            mydialog.show();

            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());

            try {
                String fileName = "myApp_" + timeStamp + ".JPG";
                String dirName= "/myApp";
                File file = new File(requireActivity().getApplicationContext().getExternalFilesDir(null).getAbsolutePath() + dirName, fileName);

                //new File(path for the file to be saved, saving file name)
                if (!file.exists()) {
                    //check if the file already exist or if not create a new file
                    //if exist the file will be overwritten with the new image
                    File filedirectory = new File(requireActivity().getApplicationContext().getExternalFilesDir(null).getAbsolutePath()  + dirName);
                    filedirectory.mkdirs();


                }
                if (file.exists()) {
                    file.delete();
                }
                FileOutputStream ostream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
                Toast.makeText(getActivity(), "Picture saved to Gallery" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                ostream.close();
                mydialog.dismiss();

                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, "My Images");
                values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
                values.put(MediaStore.MediaColumns.RELATIVE_PATH,"/myApp");
                // API LEVEL Q: values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
                values.put("_data", file.getAbsolutePath());
                ContentResolver cr = getActivity().getContentResolver();
                cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            } catch (Exception e) {
                mydialog.dismiss();
                Log.e("file creation error", e.toString());
            }

        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {
        }
        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    };

如你所见,而不是

File filedirectory = new File(Environment.getExternalStorageDirectory() + dirName);

我已经在用了

File filedirectory = new File(requireActivity().getApplicationContext().getExternalFilesDir(null).getAbsolutePath()  + dirName);

我希望这不应该是问题所在,但我有点被这种奇怪的行为所困扰

这是我从日志中发现的错误:

E/file creation error: java.lang.IllegalArgumentException: Primary directory (invalid) not allowed for content://media/external/images/media; allowed directories are [DCIM, Pictures]

PS:我使用Dexter是为了避免权限问题


共 (1) 个答案

  1. # 1 楼答案

    试试这个

    private Uri saveImage(Context context, Bitmap bitmap, @NonNull String folderName, @NonNull String fileName) throws IOException
    {
        OutputStream fos;
        File imageFile = null;
        Uri imageUri = null;
    
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolver resolver = context.getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM" + File.separator + folderName);
            imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            fos = resolver.openOutputStream(imageUri);
        } else {
            String imagesDir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM).toString() + File.separator + folderName;
            imageFile = new File(imagesDir);
            if (!imageFile.exists()) {
                imageFile.mkdir();
            }
            imageFile = new File(imagesDir, fileName + ".png");
            fos = new FileOutputStream(imageFile);
        }
    
        boolean saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    
        if (imageFile != null)  // pre Q
        {
            MediaScannerConnection.scanFile(context, new String[]{imageFile.toString()}, null, null);
            imageUri = Uri.fromFile(imageFile);
        }
    
        return imageUri;
    }
    

    并在清单文件中添加requestLegacyExternalStorage

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:requestLegacyExternalStorage="true"
        android:label="@string/app_name"
        android:roundIcon="@drawable/icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    
        ...
        ...
        ...
    
    </application>