Resize a large bitmap file to scaled output file on Android

前端 未结 21 929
执念已碎
执念已碎 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:08

    I don't know if my solution is best practice, but I achieved loading a bitmap with my desired scaling by using the inDensity and inTargetDensity options. inDensity is 0 initially when not loading a drawable resource, so this approach is for loading non resource images.

    The variables imageUri, maxImageSideLength and context are parameters of my method. I posted only the method implementation without the wrapping AsyncTask for clarity.

                ContentResolver resolver = context.getContentResolver();
                InputStream is;
                try {
                    is = resolver.openInputStream(imageUri);
                } catch (FileNotFoundException e) {
                    Log.e(TAG, "Image not found.", e);
                    return null;
                }
                Options opts = new Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, opts);
    
                // scale the image
                float maxSideLength = maxImageSideLength;
                float scaleFactor = Math.min(maxSideLength / opts.outWidth, maxSideLength / opts.outHeight);
                // do not upscale!
                if (scaleFactor < 1) {
                    opts.inDensity = 10000;
                    opts.inTargetDensity = (int) ((float) opts.inDensity * scaleFactor);
                }
                opts.inJustDecodeBounds = false;
    
                try {
                    is.close();
                } catch (IOException e) {
                    // ignore
                }
                try {
                    is = resolver.openInputStream(imageUri);
                } catch (FileNotFoundException e) {
                    Log.e(TAG, "Image not found.", e);
                    return null;
                }
                Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);
                try {
                    is.close();
                } catch (IOException e) {
                    // ignore
                }
    
                return bitmap;
    

提交回复
热议问题