Set photo size taken by phone camera

Asked

Viewed 205 times

2

I would like a help on the image save on android, I have an application that saves the image in the gallery all right, so I would like to set a size and quality for it to be sent to the server, if someone has a code that can help me.

1 answer

1

You can decrease the dimensions of an image using the Bitmapfactory.Options passed to Bitmapfactory.decodeByteArray().

Write an auxiliary method to calculate the value of BitmapFactory.Options.inSampleSize:

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {

    // Altura e largura da imagem
    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;

        //Calcula o maior valor de inSampleSize, que é uma potência de 2,
        // que mantém altura e o comprimento maiores do que os valores pedidos.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

Write a method that reads the gallery photo and returns a Bitmap with the desired size:

public static Bitmap decodeSampledBitmapFromFile(Uri fileUri,
                                                 int reqWidth, int reqHeight) {

    String path = fileUri.getPath();

    // Primeiro faz o decode com inJustDecodeBounds=true para obter as dimensões
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calcula as novas dimensões
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Faz o decode do bitmap e redimensiona
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(path);
}

Use like this:

decodeSampledBitmapFromFile(fileUri, 300, 300)

Adapted from documentation.

  • Thank you, I will test here on my application.

Browser other questions tagged

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