简体   繁体   中英

Android, Java, Creating a thumbnail keeping aspect ratio

I'm trying to create a thumbnail of a certain height but maintain the aspect ratio. I'm using the code below but the problem arises when say if an image is somewhat small the image generated 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);

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

I assume you display the image in an ImageView (your thumbnail area?. If the image does not fill the ImageView you have to configure the ImageView to resize the image correctly. If your ImageView and the image to display have different aspect ratios, the only way to make the image fill the ImageView will distort the image.

What I do: I use the BitmapFactory to decode the image into a size thats larger, but nearly the size I want the thumbnail to have. Its better to use powers of two as scaling parameter, so I do that. And then I set the android:scaleType parameter of 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM