Android, Java, creating proportions for saving thumbnails

I am trying to create a thumbnail of a certain height, but I keep the aspect ratio. I use the code below, but the problem arises when they say that if the image is somewhat small, the created image will not fill the thumbnail area. imageURI is just the path to the image.

BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(imageURI, o); final int REQUIRED_SIZE=70; int width_tmp=o.outWidth, height_tmp=o.outHeight; int scale=4; while(true){ if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) break; width_tmp/=2; height_tmp/=2; scale++; } BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize=scale; Bitmap bitmap = BitmapFactory.decodeFile(imageURI, o2); 
+4
source share
1 answer

Your code always scales the bitmap to have a width or height of at least 1/4. If the original image is already large enough, it will be even smaller.

I assume that you are displaying an image in an ImageView (thumbnail area?). If the image does not fill the ImageView, you need to configure ImageView to modify the image correctly. If your ImageView and the displayed image have different proportions, the only way to get the image to fill the ImageView will distort the image.

What I do: I use BitmapFactory to decode the image to a size that is larger, but almost the size that I want to have a thumbnail. It is better to use the powers of the two as a scaling parameter, so I do this. And then I set the android: scaleType parameter for the ImageView to make the image display as I like:

 public static Bitmap decodeBitmap(Uri bitmapUri, ContentResolver resolver, int width, int height) throws IOException{ InputStream is = resolver.openInputStream(bitmapUri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is,null,options); is.close(); int ratio = Math.min(options.outWidth/width, options.outHeight/height); int sampleSize = Integer.highestOneBit((int)Math.floor(ratio)); if(sampleSize == 0){ sampleSize = 1; } Log.d(RSBLBitmapFactory.class, "Sample Size: " + sampleSize); options = new BitmapFactory.Options(); options.inSampleSize = sampleSize; is = resolver.openInputStream(bitmapUri); Bitmap b = BitmapFactory.decodeStream(is,null,options); is.close(); return b; } <ImageView android:scaleType="fitXY"></ImageView> 
+3
source

All Articles