Creating a scaled bitmap with createScaledBitmap in Android

后端 未结 3 1991
野性不改
野性不改 2020-12-05 07:47

I want to create a scaled bitmap, but I seemingly get a dis-proportional image. It looks like a square while I want to be rectangular.

My code:

Bitma         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 08:31

    Your image is square because you are setting width = 960 and height = 960.

    You need to create a method where you pass the size of the image you want like this: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

    In code this looks like:

    public static Bitmap lessResolution (String filePath, int width, int height) {
        int reqHeight = height;
        int reqWidth = width;
        BitmapFactory.Options options = new BitmapFactory.Options();    
    
        // First decode with inJustDecodeBounds=true to check dimensions
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
    
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;        
    
        return BitmapFactory.decodeFile(filePath, options); 
    }
    
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
    
        if (height > reqHeight || width > reqWidth) {
            // Calculate ratios of height and width to requested height and width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
    
            // Choose the smallest ratio as inSampleSize value, this will guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
    

提交回复
热议问题