I'm trying to get a file from the image gallery, and then uploading it.

But before the uploading process, I want to compress the image file.

So this is the code when the picture is been choose, I'm saving the file path in a global variable (String selectedPath1) -

          if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            if (requestCode == SELECT_FILE1)
            {
                selectedPath1 = getPath(selectedImageUri);
             }
           }

Then I'm using the next code to compress the image -

  try {
        Log.d("MAIN", "1");
        compressedPictureFile = new File(selectedPath1);
        Log.d("MAIN", "2");
        Bitmap bitmap = BitmapFactory.decodeFile(selectedPath1);
        Log.d("MAIN", "3");
        FileOutputStream fOut = new FileOutputStream(compressedPictureFile);
        Log.d("MAIN", "4");
        boolean compressed = bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut);
        Log.d("MAIN", "E5");

        if (compressed){
            Log.d("MAIN", "E6");
        }else{
            Log.d("MAIN", "E7");
        }
        Log.d("MAIN", "E8");
        fOut.flush();
        fOut.close();

    } catch (FileNotFoundException e1) {
        Log.d("MAIN", "E1");
        e1.printStackTrace();
    } catch (IOException e1) {
        Log.d("MAIN", "E2");
        e1.printStackTrace();
    }

When I'm runing the code, I see in the logcat that it passing the [Log.d("MAIN", "3");] line and then it showing the - [Log.d("MAIN", "E1");] .

Meaning that the problem is at the next line -

FileOutputStream fOut = new FileOutputStream(compressedPictureFile);

So what am I doing Wrong here? How can I Solved it?

Thanks for any kind of help

有帮助吗?

解决方案

You are not created any file add this line to your code and try

compressedPictureFile = new File(selectedPath1);
    if (!compressedPictureFile.exists()) {
        compressedPictureFile.createNewFile();
    }

that too if the file path is Sd card then add this permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top