Error saving image to external storage

2

The idea of the application, is that I want to take a photo and save it with a certain name in a specific location, so far, I have: I have taken the photo, and I put it in a imageview , now, I'm going to save the picture. But when I save it, all the code goes directly to the part of: "Error during image saving".

The permissions granted to the app are:

<uses-feature android:name="android.hardware.camera"android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

I hope you can help me, or provide another code.

Here's the whole code:

package com.agustincanoalvarez.myapplication3;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    static final int REQUEST_IMAGE_CAPTURE = 1;

    Button btnCaptura,btnGuardar;

    ImageView imageView;

    int contador=0;

    Bitmap imageBitmap;



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

        btnCaptura.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureIntent();
            }
        });

        btnGuardar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Guardar();
            }
        });

    }

    private void init()
    {
        imageView =(ImageView)findViewById(R.id.imgv);
        btnCaptura =(Button)findViewById(R.id.btnCap);
        btnGuardar =(Button)findViewById(R.id.btnGuardar);

    }
    private void PictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            imageBitmap = (Bitmap) extras.get("data");
            imageView.setImageBitmap(imageBitmap);
        }
    }

    private void Guardar()
    {
        contador=contador+1;

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



        File sdCardDirectory = Environment.getExternalStorageDirectory();


        File file = new File (sdCardDirectory,"ensayo"+String.valueOf(contador)+".png");

        Toast.makeText(getApplicationContext(), "ensayo"+String.valueOf(contador)+".png",
                Toast.LENGTH_LONG).show();


        boolean success = false;

        // Encode the file as a PNG image.
        FileOutputStream outStream;
        try {

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        /* 100 to keep full quality of the image */

            outStream.flush();
            outStream.close();
            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (success) {
            Toast.makeText(getApplicationContext(), "Image saved with success",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Error during image saving", Toast.LENGTH_LONG).show();
        }
    }


}
    
asked by Agustin Cano Alvarez 21.09.2017 в 21:57
source

1 answer

2

First of all, as suggested by @WebServeis, if you use Android 6.0 or later you have to manually request the permissions:

Error when displaying the external file directory in an AlertDialog in android 6.0 (READ_EXTERNAL_STORAGE / WRITE_EXTERNAL_STORAGE)

After this you have a problem, since you are creating a file in the external memory but in the root of the external storage:

File sdCardDirectory = Environment.getExternalStorageDirectory();
File file = new File (sdCardDirectory,"ensayo"+String.valueOf(contador)+".png");

It would be created more or less in this route (varies depending on the OS):

/storage/emulated/0/ensayo12345.png

Which would cause you an error, since you can not write at this level.

You really have to add it in /Android , I usually add the files inside the path:

/storage/emulated/0/Android/data/<paquete de aplicación>/

that I do in this way:

 File sdCardDirectory = Environment.getExternalStorageDirectory();
 File file = new File (sdCardDirectory + "/Android/data/" + getPackageName(),"ensayo"+String.valueOf(contador)+".png");

or you can simply add it within /Android/data :

/storage/emulated/0/Android/data/

for example:

 File sdCardDirectory = Environment.getExternalStorageDirectory();
 File file = new File (sdCardDirectory + "/Android/data/","ensayo"+String.valueOf(contador)+".png");
    
answered by 21.09.2017 в 22:30