Unable to decode stream java.io.FileNotFoundException / storage / emulated / 0 open failed: ENOENT (No such file or directory

Hi I am trying to save photos taken in my application, but when I try to access memory to place the data, the error appears

unable to decode stream java.io.FileNotFoundException / storage / emulated / 0 open failed: ENOENT (No such file or directory)

this is my code.

            Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {

        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub
            if (data != null){
                //Intent mIntent = new Intent();
                //mIntent.putExtra("image",imageData);

                mCamera.stopPreview();
                mPreviewRunning = false;
                mCamera.release();

                 try{
                     BitmapFactory.Options opts = new BitmapFactory.Options();
                     Bitmap bitmap= BitmapFactory.decodeByteArray(data, 0, data.length,opts);
                     bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
                     int width = bitmap.getWidth();
                     int height = bitmap.getHeight();
                     int newWidth = 300;
                     int newHeight = 300;

                     // calculate the scale - in this case = 0.4f
                     float scaleWidth = ((float) newWidth) / width;
                     float scaleHeight = ((float) newHeight) / height;

                     // createa matrix for the manipulation
                     Matrix matrix = new Matrix();
                     // resize the bit map
                     matrix.postScale(scaleWidth, scaleHeight);
                     // rotate the Bitmap
                     matrix.postRotate(-90);
                     Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                             width, height, matrix, true);
                     Camera_local_db.image.setImageBitmap(resizedBitmap);

                 }catch(Exception e){
                     e.printStackTrace();
                 }
               // StoreByteImage(mContext, imageData, 50,"ImageName");
                //setResult(FOTO_MODE, mIntent);
                setResult(585);
                finish();
            }       
        }
    };


    Camera.PictureCallback jpegCallback = new Camera. PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {


        File dir_image2 = new  File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"dddd.jpg");
        dir_image2.mkdirs();  //AGAIN CHOOSING FOLDER FOR THE PICTURE(WHICH IS LIKE A SURFACEVIEW 
                                //SCREENSHOT)
        if (!dir_image2.mkdirs()) {
            Log.e(TAG, "Directory not created");
        }


        File tmpFile = new File(dir_image2,"TempGhost.jpg"); //MAKING A FILE IN THE PATH                 
                        //dir_image2(SEE RIGHT ABOVE) AND NAMING IT "TempGhost.jpg" OR ANYTHING ELSE
        try {//SAVING
            FileOutputStream fos = new FileOutputStream(tmpFile);
            fos.write(data);
            fos.close();
            //grabImage();
        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
        }
        //String path = Environment.getExternalStoragePublicDirectory(    Environment.DIRECTORY_MOVIES); File file = new File(path, "/" + dir_image2);
        //String path = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+  
          //      File.separator+"TempGhost.jpg");//<---

        BitmapFactory.Options options = new BitmapFactory.Options();//<---
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;//<---
        bmp1 = BitmapFactory.decodeFile(tmpFile.toString(), options);//<---
        //THE LINES ABOVE READ THE FILE WE SAVED BEFORE AND CONVERT IT INTO A BitMap
        Camera_local_db.image.setImageBitmap(bmp1);
        //camera_image.setImageBitmap(bmp1); //SETTING THE BitMap AS IMAGE IN AN IMAGEVIEW(SOMETHING
                                    //LIKE A BACKGROUNG FOR THE LAYOUT)
       // TakeScreenshot();//CALLING THIS METHOD TO TAKE A SCREENSHOT

    }
    };

      

+3


source to share


5 answers


You need to write external storage, make sure you add permission:

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

      

Checks for external read / write storage:

public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

      

Use the root of the public directory instead of using the root of Android.



If you want to keep public files in external storage use getExternalStoragePublicDirectory ()

public File getAlbumStorageDir(String albumName) {
    // Get the directory for the user public pictures directory. 
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DCIM), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

      

If you want to keep files that are private to your application use getExternalFilesDir ()

public File getAlbumStorageDir(Context context, String albumName) {
    // Get the directory for the app private pictures directory. 
    File file = new File(context.getExternalFilesDir(
            Environment.DIRECTORY_DCIM), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

      

More info at http://developer.android.com/training/basics/data-storage/files.html

+7


source


I had the same error and the only problem was permission in android manifest.



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


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

      

+4


source


First, you write the image in a different place than you read it. Instead of rebuilding path

, use the value tmpFile

you already have.

Second, don't use getRootDirectory()

to get a directory DCIM

. Use getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)

.

Third, use methods Log

to log exceptions instead of just displaying Toast

as you can skip Toast

and you won't get the stack trace associated with your exception.

+3


source


I decided to use this:

private static final int WRITE_PERMISSION = 0x01;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestWritePermission();
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if(requestCode == WRITE_PERMISSION){
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.d(LOG_TAG, "Write Permission Failed");
            Toast.makeText(this, "You must allow permission write external storage to your mobile device.", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}

private void requestWritePermission(){
    if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},WRITE_PERMISSION);
    }
}

      

+2


source


Add this permission to your Android manifest.

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

      

If it fails with this permission already present, you need to check the target SDK level on your application. If it's targetSdkVersion => 23 then you need to ask for permissions at runtime. Here

0


source







All Articles