简体   繁体   中英

Upload image to firebase storage, from the camera android

I have a problem with my code, I have to upload images to the firebase storage, I need the images to come from the gallery and the camera, the images from the gallery are ok, but the images coming from the camera are giving problem, image which loads in the imageView and is sent to the database is black. Does anyone know how to fix this, or do you know any other method to load image?

the project code

//Funçao de escolha das opcoes de upload---------------------------------------------------------
private void jeitoImagem() {

    final CharSequence[] jeito = {"Camera", "Galeria", "Cancelar"};

    //Alert Dialog com as opçoes de escolha-----------------------------------------------------
    AlertDialog.Builder b = new AlertDialog.Builder(CadastroEmpresaActivity.this, R.style.Theme_AppCompat_Light_Dialog_Alert);
    b.setTitle("Adicionar imagem");
    b.setItems(jeito, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if(jeito[i].equals("Camera")){
                abrirCamera();

            } else if(jeito[i].equals("Galeria")){
                abrirGaleria();

            } else if(jeito[i].equals("Cancelar")){
                dialogInterface.dismiss();
            }

        }
    });

    b.create();
    b.show();



}

//Funçao de upar imagem da galeria--------------------------------------------------------------
public void abrirGaleria() {
    Intent i = new Intent(Intent.ACTION_PICK);
    i.setType("image/*");
    startActivityForResult(i,GALERIA);
}

//Funçao de upar imagem da camera---------------------------------------------------------------
public void abrirCamera() {
    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i, CAMERA);
}

OnActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //passando o data pra variavel uri----------------------------------------------------------
    uri = data.getData();

    //Verificando a opçao que foi selecionada---------------------------------------------------

from gallery

    if(requestCode == GALERIA && resultCode == RESULT_OK && uri != null){
        //Chamando instancia do Storage---------------------------------------------------------
        storageReference1 = FirebaseStorage.getInstance().getReference();
        try {
            //Setando imagem no imageView-------------------------------------------------------
            Bitmap b = MediaStore.Images.Media.getBitmap(CadastroEmpresaActivity.this.getContentResolver(), uri);
            imagem.setImageBitmap(b);

            //Chamando o Storage pra salvar a imagem--------------------------------------------
            StorageReference ref  = storageReference1.child("Usuario" + System.currentTimeMillis() +".MiBuy");

            ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    //Passando url da imagem pra variavel---------------------------------------
                    urlImage = taskSnapshot.getDownloadUrl().toString();

                    //Alert Dialog de aviso do upload da imagem---------------------------------
                    AlertDialog.Builder b = new AlertDialog.Builder(CadastroEmpresaActivity.this, R.style.Theme_AppCompat_Light_Dialog_Alert);
                    b.getContext();
                    b.setTitle(R.string.upload_imagem);
                    b.setMessage(R.string.texto_upload_imagem);
                    b.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();

                        }
                    });
                    b.create();
                    b.show();




                }
            });




        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Verificando a opçao que foi selecionada---------------------------------------------------

from camera

     if (requestCode == CAMERA && resultCode == RESULT_OK){
        //Chamando instancia do Storage---------------------------------------------------------
        storageReference2 = FirebaseStorage.getInstance().getReference();
        //Caminho da URL------------------------------------------------------------------------
        StorageReference mref = storageReference2.child("Usuario"+ System.currentTimeMillis()+"MiBuy");

        //Liberando cache nas imagens-----------------------------------------------------------
        imagem.setDrawingCacheEnabled(true);
        imagem.buildDrawingCache();

        //Criando bitmap------------------------------------------------------------------------

        Bitmap bitmap = imagem.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] dd = baos.toByteArray();

        //Upando a imagem pro firebase----------------------------------------------------------
        UploadTask uploadTask = mref.putBytes(dd);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                //Alert Dialog de aviso de erro no upload da imagem-----------------------------
                AlertDialog.Builder b = new AlertDialog.Builder(CadastroEmpresaActivity.this, R.style.Theme_AppCompat_Light_Dialog_Alert);
                b.getContext();
                b.setTitle(R.string.erro_upload_imagem);
                b.setMessage(R.string.texto_erro_upload_imagem);
                b.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();

                    }
                });
                b.create();
                b.show();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                //Alert Dialog de aviso do upload da imagem-------------------------------------
                AlertDialog.Builder b = new AlertDialog.Builder(CadastroEmpresaActivity.this, R.style.Theme_AppCompat_Light_Dialog_Alert);
                b.getContext();
                b.setTitle(R.string.upload_imagem);
                b.setMessage(R.string.texto_upload_imagem);
                b.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();

                    }
                });
                b.create();
                b.show();

                //Passando url da imagem pra variavel-------------------------------------------
                Uri ddownload = taskSnapshot.getDownloadUrl();
                urlImage = taskSnapshot.getDownloadUrl().toString();

                //Colocando imagem no imageView
                Picasso.with(CadastroEmpresaActivity.this).load(ddownload).into(imagem);

            }
        });


    }

}

The intent you are using to start the camera app returns only a thumbnail image , which you can obtain from the returned data:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        ...
        mImageView.setImageBitmap(imageBitmap);
    }
}

If you want to get a full-size image you must create a file to hold the image, create a URI for the file, and add the URI to the intent as an extra. This is described in the documentation .

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