//How to limit the height and width of the image when taking it from the File Picker
CodePudding user response:
You can use the BitmapFactory
class to decode the image and specify the maximum height and width you want for the image. Like this:
// set desired dimensions for the image
int targetWidth = 200;
int targetHeight = 200;
// get dimensions of original image
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, bmOptions);
int photoWidth = bmOptions.outWidth;
int photoHeight = bmOptions.outHeight;
// determine how much to scale down image
int scaleFactor = Math.min(photoWidth / targetWidth, photoHeight / targetHeight);
// decode image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
CodePudding user response:
You can use the BitmapFactory
class to decode the image file and specify the desired width and height in the BitmapFactory.Options
object. Example:
// Get the file path from the File Picker
String filePath = // ...
// Decode the image file into a Bitmap
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate the desired size
int desiredWidth = 200;
int desiredHeight = 200;
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
if (height > desiredHeight || width > desiredWidth) {
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) >= desiredHeight
&& (halfWidth / inSampleSize) >= desiredWidth) {
inSampleSize *= 2;
}
}
// Decode the image file into a Bitmap with the desired size
options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
This will decode the image file into a Bitmap object with a width and height that is at most desiredWidth and desiredHeight, respectively.