3

Estoy creando una app en la que el usuario puede poner foto de perfil. Con el suguiente uri uri consigo que el usuario suba su foto.(pero las fotos pueden tener tamaños muy grandes de mas de 2Mb)

       final Uri uri = data.getData();

Por eso necesito que se suba solo el bitmap de la foto.(que se reduzca el tamaño de la foto antes de subirla a firebase). Les pongo mi código de subida de imágenes:

Selecciono una foto:

subirFoto =(ImageView) findViewById(R.id.subir_foto);
    subirFoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent subirIntent = new Intent();
            subirIntent.setType("image/*");
            subirIntent.setAction(Intent.ACTION_GET_CONTENT);
            if (subirIntent.resolveActivity(getPackageManager()) !=null){
                startActivityForResult(Intent.createChooser(subirIntent, "Sube una foto"), CAMERA_REQUEST_CODE);
            }
        }
    });

La subo a firebase:

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

    if (requesCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
        if (mAuth.getCurrentUser() == null)
            return;
        mProgress.setMessage("Cargando imagen...");
        mProgress.show();

        //final Bitmap photos?????

        final Uri uri = data.getData();
        if (uri == null){
            mProgress.dismiss();
            return;
        }


        if (mAuth.getCurrentUser() == null)
            return;
        if (mStorage == null)
            mStorage = FirebaseStorage.getInstance().getReference();
        if (mDatabase == null)
            mDatabase = FirebaseDatabase.getInstance().getReference().child("photos");

        final StorageReference filepath = mStorage.child("Products").child(mRandomString());
        final DatabaseReference currentUserDB = mDatabase.child(mAuth.getCurrentUser().getUid());
        currentUserDB.child("image").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String image = dataSnapshot.getValue().toString();

                if (!image.equals("default") && !image.isEmpty()){
                    Task<Void> task = FirebaseStorage.getInstance().getReferenceFromUrl(image).delete();
                    task.addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful())
                                Toast.makeText(Publicando.this, "Refrescando...", Toast.LENGTH_LONG).show();
                            else
                                Toast.makeText(Publicando.this, "Imagen no borrada", Toast.LENGTH_LONG).show();

                        }
                    });
                }
                currentUserDB.child("image").removeEventListener(this);


                filepath.putFile(uri)


 .addOnProgressListener(Publicando.this, new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                        int currentprogress = (int) progress;

                        double cargado = (taskSnapshot.getBytesTransferred()/1024);
                        double total = (taskSnapshot.getTotalByteCount()/1024);
                        int cargaActual = (int) cargado;

                        mProgress.setMessage("Cargando "+cargaActual+"/"+total+" KB" + " ("+currentprogress+"%"+")");
                        mProgress.setCanceledOnTouchOutside(false);
                        //System.out.println("Upload is " + progress + "% done");
                        // mProgress.setMessage("Carga a "+currentprogress+"%");
                        //Toast.makeText(Publicando.this, "Cargando "+currentprogress, Toast.LENGTH_LONG).show();

                    }

                }).addOnSuccessListener(Publicando.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        mProgress.dismiss();
                        Uri downloadUri = taskSnapshot.getDownloadUrl();
                        Toast.makeText(Publicando.this, "Finalizado", Toast.LENGTH_LONG).show();

                        Picasso.with(Publicando.this).load(uri).fit().centerCrop().into(subirFoto);
                        DatabaseReference currentUserDB = mDatabase.child(mAuth.getCurrentUser().getUid());
                        currentUserDB.child("image").setValue(downloadUri.toString());

                    }
                }).addOnFailureListener(Publicando.this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        mProgress.dismiss();
                        Toast.makeText(Publicando.this, e.getMessage(), Toast.LENGTH_LONG).show();

                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(Publicando.this, "Carga interumpida", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Gracias anticipadas!

2 respuestas 2

1

Te paso un solución que estaba en StackOverflow

public static Bitmap reducirImagen(Context c, Uri uri, final int requiredSize) 
            throws FileNotFoundException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;http://es.stackoverflow.com/questions/37764/c%c3%b3mo-subir-bitmap-a-firebase-storage#
        BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o);

        int width_tmp = o.outWidth
                , height_tmp = o.outHeight;
        int scale = 1;

        while(true) {
            if(width_tmp / 2 < requiredSize || height_tmp / 2 < requiredSize)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o2);
    }   
3
  • El OP desea subir la imagen a Firebase Storage.
    – Jorgesys
    el 6 dic. 2016 a las 16:48
  • No me funcionó: 1. no sé cómo aplicar este código en mi onActivityResult 2. me parece que este código redimenciona el alto y ancho de las imágenes. Recuerda que necesito reducir el tamaño en bytes (conseguir que una imagen de 2000 kb se reduzca a 200kb, por ejemplo)
    – Tony_Bielo
    el 6 dic. 2016 a las 19:39
  • 1.- Pues hay mucha información al respecto de como llamar a un método en Java. 2.- Como dice la respuesta original con este método you can avoid OutOfMemoryError, o lo que es lo mismo, también se reduce el peso de la imagen en bytes, si lo que necesitas es un peso especifico 200kb, por ejemplo, deberías aclararlo en tu pregunta. el 7 dic. 2016 a las 12:08
1

Gracias por la respuesta. Finalmente conseguí lo que necesitaba. Lo he conseguido combinado varias respuestas que he encontrado en este sitio. En mi

onActivityResult

He añadido las siguientes lineas:

final Uri imageUri = data.getData();

        //Uri uri = data.getData();
        if (imageUri == null){
            mProgress.dismiss();
            return;
        }


        //Bitmap bitmap = subirFoto.getDrawingCache();

        Bitmap bitmap = null;
        try {
            bitmap =    MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        subirFoto.setDrawingCacheEnabled(true);
        subirFoto.buildDrawingCache();
        //subirFoto.setImageBitmap(bitmap);

        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        bmOptions.inSampleSize = 1;
        bmOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
        bmOptions.inJustDecodeBounds = false;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 10, baos);
        final byte[] foto = baos.toByteArray();

Y para subir la foto a firebase reduciendo el tamaño (por ejemplo de 3.000 kb a 215 kb) ojo! sin reducir las propiedades de ancho y largo :

UploadTask uploadTask = filepath.putBytes(foto);

Controlo el proceso de subida:

uploadTask.addOnProgressListener(new OnProgressListener...

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.