Show Images Camera / Gallery and Upload them to FireBase

0

I have an APP with which I can choose to take a photo with the Camera or choose it from the Gallery.

If I choose it from the gallery, the image is uploaded and displayed correctly, but if I use the option to make an image with the camera, the image is displayed but it is not uploaded.

Whole Code

public class Fotos extends AppCompatActivity {

    //Controles para la camara/galeria
    private static String APP_DIRECTORY = "MyPictureApp/";
    private static String MEDIA_DIRECTORY = APP_DIRECTORY + "PictureApp";

    private final int PHOTO_CODE = 200;
    private final int SELECT_PICTURE = 300;

    private String mPath;
    private Bitmap imageBitmap;

    private StorageReference mStorage;

    ImageView foto;


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

        foto = (ImageView) findViewById(R.id.foto);

        mStorage = FirebaseStorage.getInstance().getReference();

        //Botones para abrir las Actividades (Camara/Galeria/Siguiente)
        Button camara = (Button) findViewById(R.id.camara1);
        camara.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openCamera();
            }
        });

        //Metodo para abrir la Galeria
        Button galeria = (Button) findViewById(R.id.galeria);
        galeria.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openGaleria();
            }
        });

        //Metodo para pasar la foto a la Actividad MenuAvisos
        Button siguiente = (Button) findViewById(R.id.siguiente);
        siguiente.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                openSiguiente();
            }
        });
    }

    //Metodo para abrir la Camara de Fotos
    private void openCamera()
    {
        File file = new File(Environment.getExternalStorageDirectory(), MEDIA_DIRECTORY);
        boolean isDirectoryCreated = file.exists();

        if(!isDirectoryCreated)
            isDirectoryCreated = file.mkdirs();

        if(isDirectoryCreated)
        {
            Long timestamp = System.currentTimeMillis() / 1000;
            String imageName = timestamp.toString() + ".jpg";

            mPath = Environment.getExternalStorageDirectory() + File.separator + MEDIA_DIRECTORY + File.separator + imageName;

            File newFile = new File(mPath);

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile));

            startActivityForResult(intent, PHOTO_CODE);
        }
    }

    private Bitmap drawableToBitmap (Drawable drawable)
    {
        Bitmap bitmap = null;

        if(drawable instanceof BitmapDrawable)
        {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if(bitmapDrawable.getBitmap() !=null)
            {
                return bitmapDrawable.getBitmap();
            }
        }

        if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0)
        {
            bitmap = Bitmap.createBitmap(1,1, Bitmap.Config.ARGB_8888);
        }
        else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0,0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

    //Depende la seleccion de Camara/Galeria (Case) hace una cosa o otra para mostrar las imagenes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK){
            switch (requestCode){
                case PHOTO_CODE:
                    MediaScannerConnection.scanFile(this, new String[] { mPath }, null, new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned" + path + ":");
                            Log.i("ExternalStorage", "-> Uri = " + uri);

                            uri = data.getData();
                            StorageReference filePath = mStorage.child("Fotos Aviso").child(uri.getLastPathSegment());
                            filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                    Toast.makeText(Fotos.this, "Se ha subido la foto a FireBase!", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    });
                    imageBitmap = BitmapFactory.decodeFile(mPath);
                    //Mostrar foto
                    foto.setImageBitmap(imageBitmap);
                    break;
                case SELECT_PICTURE:
                    //FireBase Storage
                    Uri path = data.getData();
                    StorageReference filePath = mStorage.child("Fotos Aviso").child(path.getLastPathSegment());
                    filePath.putFile(path).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Toast.makeText(Fotos.this, "Se ha subido la foto a FireBase!", Toast.LENGTH_SHORT).show();
                        }
                    });
                    //Mostrar la imagen
                    foto.setImageURI(path);
                    imageBitmap = drawableToBitmap(foto.getDrawable());
                    break;
            }
        }
    }

    //Metodo para abrir la Galeria
    private void openGaleria()
    {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");

        startActivityForResult(intent.createChooser(intent, "Selecciona app de imagen"), SELECT_PICTURE);
    }

    //Metodo para enviar la foto a la Actividad MenuAvisos*
    private void openSiguiente()
    {
        Intent intent=new Intent();
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, 200, 150, true);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG,50,bs);
        intent.putExtra("MESSAGE",bs.toByteArray());
        setResult(RESULT_OK,intent);

        finish();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString("file_path", mPath);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        mPath = savedInstanceState.getString("file_path");
    }
}
    
asked by Cristian Prieto Beltran 18.05.2017 в 11:19
source

1 answer

0

Try these two methods.

First, your modified openCamera method.

private void openCamera(String nombreArchivoPrivado) {
// Se guarda el nombre para uso posterior.
sNombreArchivo = nombreArchivoPrivado;
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Si hay alguna actividad que sepa realizar la acción.
if (i.resolveActivity(getPackageManager()) != null) {
    // Se crea el archivo para la foto en el directorio público (true).
    // Se obtiene la fecha y hora actual.
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    String nombre = "IMG_" + timestamp + "_" + ".jpg";
    File fotoFile = crearArchivoFoto(nombre, true);
    if (fotoFile != null) {
        // Se guarda el path del archivo para cuando se haya hecho la captura.
        sPathFotoOriginal = fotoFile.getAbsolutePath();

        Uri fotoURI = Uri.fromFile(fotoFile);
        // Se añade como extra del intent la uri donde debe guardarse.
        i.putExtra(MediaStore.EXTRA_OUTPUT, fotoURI);
        startActivityForResult(i, RC_CAPTURAR_FOTO);
    }
}
}

Then the createfile method used for:

File new File = crearArchivoFoto(nombre, true);

Here.

 private File crearArchivoFoto(String nombre, boolean publico) {
 // Se obtiene el directorio en el que almacenarlo.
 File directorio; 
 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    if (publico) {
        // En el directorio público para imágenes del almacenamiento externo.
        directorio = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    } else {
        directorio = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    }
} else {
    // En almacenamiento interno.
    directorio = getFilesDir();
}
// Su no existe el directorio, se crea.
if (directorio != null && !directorio.exists()) {
    if (!directorio.mkdirs()) {
        Log.d(getString(R.string.app_name), "error al crear el directorio");
        return null;
    }
}
// Se crea un archivo con ese nombre y la extensión jpg en ese
// directorio.
File archivo = null;
if (directorio != null) {
    archivo = new File(directorio.getPath() + File.separator +
            nombre);
    Log.d(getString(R.string.app_name), archivo.getAbsolutePath());
}
// Se retorna el archivo creado.
return archivo;

}

ActivityResult. Same as yours.

Uri uriGaleria = intent.getData();

StorageReference filePath = mStorage.child("Fotos Aviso").child(path.getLastPathSegment());
filePath.putFile(path).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
     @Override
     public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
           Toast.makeText(Fotos.this, "Se ha subido la foto a FireBase!", Toast.LENGTH_SHORT).show();
     }
  });
    
answered by 18.05.2017 в 13:51