简体   繁体   中英

Android IOException when compressing a Bitmap

In my Android project I am trying to save a bitmap to the SD card at a given location.

When I run this, I get an IOException every time, saying permission denied. This is on creating the FileOutputStream.

This leads me to believe that I am missing permissions, but I include READ and WRITE_EXTERNAL_STORAGE . They are declared before my uses-sdk block and are outside the application block. I also read/write text to a file elsewhere in my application and that works just fine. My current code was modified to match several of the solutions I found online, but I have not been able to successfully save a bitmap file.

If anyone could point out my error I would be extremely thankful.

    ImageView imageView = (ImageView) findViewById(R.id.new_pnm_pic);
    Bitmap bm = (Bitmap)data.getExtras().get("data");
    imageView.setImageBitmap(bm);
    String outPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recruits";

    try {
          File d = new File(outPath);
          if (!d.exists())
          d.mkdirs();

          SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
          String currentTime = sd.format(new Date());

          File file = new File(outPath+'/'+currentTime+".jpg");             
          FileOutputStream fOut = new FileOutputStream(file.getPath());

          bm.compress(Bitmap.CompressFormat.JPEG, 50, fOut);

          fOut.flush();
          fOut.close();

       }
   catch(IOException ioe){
     Toast.makeText(this, "Nice try but didn't work", Toast.LENGTH_SHORT).show();
        }

Change This

File file = new File(outPath+'/'+currentTime+".jpg");


To

File file = new File(d+'/'+currentTime+".jpg");

And Add Permission to Manifest File:-

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Edit
Before we start saving the image to sd card ,we need to check whether the sd card is mounted or not .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM