Resize an image before uploading to Firebase

Asked

Viewed 769 times

0

I want to resize the image that is in imageView coming from a camera or gallery before sending to Firebase, as you can see is being sent the "filepath" that is a Ri so I can not use scaleDown code. I am sending the image to the firebase Storage and the link goes to database. How can I resize before sending?

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == PICK_IMAGE_REQUEST || requestCode == REQUEST_IMAGE_CAPTURE) && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            if (requestCode == PICK_IMAGE_REQUEST) {

                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    imageView.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (requestCode == REQUEST_IMAGE_CAPTURE) {
                filePath = data.getData();
                Uri selectedImageUri = data.getData();
                imageView.setImageURI(selectedImageUri);

            }
        }
    }

>

StorageReference sRef = storageReference.child(Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + "." + getFileExtension(filePath));

                //adding the file to reference
                sRef.putFile(filePath)
                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                //dismissing the progress dialog
                                progressDialog.dismiss();

                                //displaying success toast
                                Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();


                                //creating the upload object to store uploaded image details
                                Upload upload = new Upload(editTextName.getText().toString().trim(), editTextName1.getText().toString().trim(), editTextName2.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString());


                                String uploadId = mDatabase.push().getKey();
                                mDatabase.child(uploadId).setValue(upload);



                            }
                        })

Scaleimage

public static Bitmap scaleDown(Bitmap realImage, float maxImageSize, boolean filter) {
    float ratio = Math.min(
    (float) maxImageSize / realImage.getWidth(),
    (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,height, filter);
    return newBitmap;
}

2 answers

1

Could use Bitmapfactory:

    ParcelFileDescriptor parcelFileDescriptor =
                        context.getContentResolver().openFileDescriptor(uri, "r");

    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
    options.inSampleSize = calculateInSampleSize(options, BITMAP_MAX_SIZE, BITMAP_MAX_SIZE);
    options.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

    parcelFileDescriptor.close();

Note that BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); with options.inJustDecodeBounds = true; will return to you null , but you will have options.outWidthand options.outHeight in order to calculate options.inSampleSize and then decode the bitmap again, but then yes with options.options.inJustDecodeBounds = false;

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}
  • How would you implement this first code, put it inside onActivityResult? would change openFileDescriptor(Uri, "r"); to openFileDescriptor(filepath, "r");

  • Yes, it would be inside the onActivityResult or in a method the part, as you prefer. Would change openFileDescriptor(Uri, "r") to openFileDescriptor(selectedImageUri, "r"). I think the idea is to move the bitmap to the right firebase? Then you would pass the bitmap back to the storageReference

  • André, I’m having trouble implementing, what would be Roundedbitmapdrawableutil, is a method? , how to implement since I used two means, camera and gallery.

  • Roundedbitmapdrawableutil would be the class where the calculateInSampleSize method is in my project. In both cases in onActivityResult() the.getData() date returns you to Uri. And then just pass to the context.getContentResolver(). openFileDescriptor(Uri, "r"); (first line of the example)

  • Sorry André but I don’t understand, you have to edit my code and show how to implement your code? I appreciate your help.

0

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

    if (resultCode == RESULT_OK && requestCode == 0) {
        ImageView img = (ImageView)
                findViewById(R.id.imageFoto);

        // Obtém o tamanho da ImageView
        int targetW = img.getWidth();
        int targetH = img.getHeight();

        // Obtém a largura e altura da foto
        BitmapFactory.Options bmOptions =
                new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(
                caminho_foto.getAbsolutePath(), bmOptions);

        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determina o fator de redimensionamento
        int scaleFactor = Math.min(
                photoW/targetW, photoH/targetH);

        // Decodifica o arquivo de imagem em
        // um Bitmap que preencherá a ImageView
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(
                caminhoDafoto.getAbsolutePath(), bmOptions);
        img.setImageBitmap(bitmap);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.