Java tutorial
//package com.java2s; /* * Copyright (C) 2017 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import java.io.IOException; import java.io.InputStream; public class Main { public static Bitmap decodeSampledBitmapFromStream(Context context, Uri uri, int reqWidth, int reqHeight) throws IOException { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; InputStream stream = context.getContentResolver().openInputStream(uri); BitmapFactory.decodeStream(stream, null, options); stream.close(); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; stream = context.getContentResolver().openInputStream(uri); Bitmap bmp = BitmapFactory.decodeStream(stream, null, options); stream.close(); return bmp; } private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; int minSize = Math.max(reqWidth, reqHeight); if (height > minSize || width > minSize) { final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) > minSize && (halfWidth / inSampleSize) > minSize) { inSampleSize *= 2; } } return inSampleSize; } }