Resize a large bitmap file to scaled output file on Android

前端 未结 21 930
执念已碎
执念已碎 2020-11-22 05:51

I have a large bitmap (say 3888x2592) in a file. Now, I want to resize that bitmap to 800x533 and save it to another file. I normally would scale the bitmap by calling

21条回答
  •  感情败类
    2020-11-22 06:18

    Acknowledging the other excellent answer so far, the best code I've seen yet for this is in the documentation for the photo taking tool.

    See the section entitled "Decode a Scaled Image".

    http://developer.android.com/training/camera/photobasics.html

    The solution it proposes is a resize then scale solution like the others here, but it's quite neat.

    I've copied the code below as a ready-to-go function for convenience.

    private void setPic(String imagePath, ImageView destination) {
        int targetW = destination.getWidth();
        int targetH = destination.getHeight();
        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;
    
        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
    
        // Decode the 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);
        destination.setImageBitmap(bitmap);
    }
    

提交回复
热议问题